vendredi 29 juin 2018

2D array removes its elements after exiting the loop

Input is: hello world
The following program should record "hello" in words[0] and "world in words[1]

int rowIndex= 0;
char words [100][100];
for (int x = 0 ; x < input.length(); x++)
{
  if (input[x]>='a'&&input[x]<='z' || input[x]>='A'&&input[x]<='Z')
 // This condition is to avoid recording spaces in the array
  {
      words[rowIndex][x]= input[x];
      cout << words[rowIndex][x]<<" ";
  }
  else {
    rowIndex++;
    // Once it finds a space, it records the following characters into the next index
    cout << " Index: " << rowIndex <<endl;
  }
}

output:
h e l l o
Index: 1
w o r l d

cout <<"Index 0: "<< words[0] <<endl;

Output: hello

cout <<"Index 1: "<< words[1] <<endl;

Output: " doesn't output anything" ( Why doesn't it output "world")
*****************************************************
Why doesn't the array hold the characters in words[1] and only holds the characters in words[0]
Note: I tried doing it with dynamic 2D array and same problem happened.

Aucun commentaire:

Enregistrer un commentaire