c++ - cin in a while-loop -
#include <iostream> using namespace std; int main() { string previous; string current; while (cin >> current) { if(current == previous) { cout << "repeated word"; } previous=current; } return 0; }
my questions are:
when states
while(cin>>current)
, why entire entered string of text not assigned current? don't understand how compares words individually.how word previous. how know 2 of same words adjacent?
edit: think understood why. tell me if wrong think because compiler stops cin
assignment @ space , first word assigned current, compares previous word, since first word, not have previous word assigned first word previous , compares next word in sentence until there no more words left. i'm how works going leave in case ever wondering similar.
- the default behavior stop on whitespace when reading strings doing. can change read whitespace saying
std::cin >> std::noskipws
. - the previous word assigned @ end of loop. given answer part 1, should clear why previous works.
Comments
Post a Comment