I can't figure out certain parts of this code. Any help is greatly appreciated.
Specifically I dont really understand the words array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
using namespace std;
int main()
{
char line[100] =
"This is a text from mi nights";
int numberOfWords
words[0] = 0;
numberOfWords = 1;
for (int i = 0; line[i] != '\0'; i = i + 1)
if (line[i] == ' ')
{
line[i] = '\0';
words[numberOfWords] = i + 1;
numberOfWords ++;
}
for (int i = 0; i<numberOfWords; i++)
{
cout << "A word: ";
for (int j = words[i]; line[j] != '\0'; j = j + 1)
cout << line[j];
cout << endl;
}
}
|
1 2 3 4 5 6 7 8 9
|
char line[100] =
"This is a text from mi nights";
int words[20];
int numberOfWords;
words[0] = 0;
numberOfWords = 1;
|
OK so here I declare and initialize my variables and arrays. So far so good. Im not understanding why words[0] is put to o and numberOfWords is put to 1.
1 2 3 4 5 6 7 8
|
for (int i = 0; line[i] != '\0'; i = i + 1)
if (line[i] == ' ')
{
line[i] = '\0';
words[numberOfWords] = i + 1;
numberOfWords++;
}
|
Here I know I will loop through the line array and since its a char array it will stop at \0. Then the if statement says that 'space' equals \0 so itl stop as soon as it encounters a space. Thus creating a new string each time it hits \0. Since I didnt quite understand the use of words[] before, Im absolutely clueless what words[numberOfWords]does here and why it is set equal to i+1. Afterward numberOfWords is incremented after every loop, I get it and I think once I understand the meaning of this : words[numberOfWords] = i + 1 the increment will make sense as well.
1 2 3 4 5 6 7 8
|
for (int i = 0; i<numberOfWords; i++)
{
cout << "A word: ";
for (int j = words[i]; line[j] != '\0'; j = j + 1)
cout << line[j];
cout << endl;
}
|
Im not quite sure if what i think I understood here is right. Actually my problem starts with the first for loop, as I dont understand the condition why i<numberOfWords. What it does is it prints "A word" to the console before every other word that is printed out.
OK so the second for loop. Well j is set to words[i] which is 0. So line[j] is really line[words[0]] and 0 is incremented by one after every loop. The problem is again that I cant understand the meaning of the words array. What is its use. Why and how does it interact with the line array. Why is it set to 0 in line 12. And Why is numberOfWords = 1 in line 13.
Thanks so very much for your help. Im basically all on my own trying to figure this out and Im having a hell of a hard time doing it.