-1

I'm a beginner in C++ and I've using Programming: Principles and Practice from Bjarne Stroustrup. I've gotten to the assignment chapter and came across this example

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;
        }
}

But I don't quite understand the logic behind it, mainly in the first through of the loop, where previous=" ", i dont know how previous get to equal anything at all from the input in current given that it values " ". If I compile and input " the cat cat eats" it identifies cat as the repeated word but how does it know since, like the comment says, its initialized to no word, why does it cout the repeated word: cat in that first case.

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • think about `previous = current;` line, what it does? – Iłya Bursov Jun 30 '21 at 18:43
  • it assign a new value, current, to previous? – ninoprovezano Jun 30 '21 at 18:56
  • Are you compiling and running that example code? You should be able to add a cout statement that shows the value of `previous` and `current` inside the loop. The transcript of the output it produces might help you understand how it works. Good old [printf debugging](https://stackoverflow.com/questions/189562/what-is-the-proper-name-for-doing-debugging-by-adding-print-statements) so-to-speak. – Wyck Jun 30 '21 at 19:29

1 Answers1

1

At the end of the loop iteration, you are assigning current value to previous (previous = current). At the start of new iteration, you are assigning user entered value to current value and comparing with previous.

kadina
  • 5,042
  • 4
  • 42
  • 83