Originally Posted by
jimblumberg
Do you mean the if() statement inside the while loop doesn't execute as you expect?
I don't expect that code to ever execute, since previous will probably never equal current.
Also your comments are mostly incorrect.
Code:
string previous = " "; // previous word; initialized to a single space.
string current; // current word
while (cin >> current) // read a word from the console.
The previous = current; line should probably be outside the if statement.
Jim
It's taken from Stroustrup's book exactly as is, so it probably works for him somehow but not for us. If that's even possible.
So you're saying I should declare do previous = current outside the if-statment?
Edit: It's working perfectly now
I probably just got confused due to Stroustrup's lack of use of curly-braces in his if-statement and while-loop code.
This is what he's got in there that through me off:
Code:
int main()
{
int number_of_words = 0;
string previous = " "; // not a word
string current;
while (cin>>current) {
++number_of_words; // increase word count
if (previous == current)
cout << "word number " << number_of_words
<< " repeated: " << current << '\n';
previous = current;
}
}
You can tell that previous = current is outside the if-statment, but someone like me who is used to seeing curly-braces will probably have a hard time at first. Ah, well.
Edit2: And by the way, that example code is an improvement on this one:
Code:
int main()
{
string previous = " "; // previous word; initialized to “not a word”
string current; // current word
while (cin>>current) { // read a stream of words
if (previous == current) // check if the word is the same as last
cout << "repeated word: " << current << '\n';
previous = current;
}
}
And that's where most of the comments came from.