So I am having a bit of confusion with understanding WHY this program works.
1 2 3 4 5 6 7 8 9 10 11 12
#include "std_lib_facilities.h"
int main()
{
string previous =" "; // previous word is "not a word"
string current; // current word
while (cin>>current){ // read a stream of words
if (previous==current) // check if the current word is same as the last
cout<<"repeated word: "<<current<<'\n';
previous = current;
}
}
Questions:
(1) Looking at line 7, how does (cin>>current) work? For example, I may say make my input "The cat cat jumped." but I don't understand how the word "cat" is isolated by the program.
(2) Does the (cin>>current) take my sentence one grouped character at a time? For example, is it interpreted as "The", "cat", "cat", "jumped", "."?
(3) What is the point of the last part (previous = current)? I don't understand how the previous variable is working.
Well, what is happening here is that it first sets the previous word to a space, and leaves the current word blank. Then what happens is that when you input into the string current (which is what the while loop does- as long as there is input, it will keep going) which can only hold a single word due to using cin, it checks it against what is held in previous. After that, it stores the newly-added word into previous so that the next word would be checked against that.
More specifically to your questions:
1) cin only takes input up until a space. So yes, it does break it into individual words.
2) Yes, for cin only takes one-word inputs.
3) Previous is the word immediately before the word it is checking. If it is equal to the new word inputted, then there is a repeat.