This code is just to realize a function that when you input twice same strings,
the function stops.
string predata;
string c_data; //current data
cout << "please input string data" << endl;
//loop
while (cin >> c_data) {
if (c_data == predata) {
cout << "the " << c_data << " is the same one" << endl;
break;
}
else {
predata = c_data;
}
cout << "please input next word" << endl;
}
if (c_data != predata)
cout << "there's no repeated word" << endl;
Question: When I use CTRL-D to stop cin, the c_data is not change, and it will never output “there’s no repeated word”, so how can I decide the judgement ?
PS: This is one exercise in 《c++ primer》, and the code in answer book didn’t solve the problem too.
You aren’t too specific about what you’ve entered previously. When
>>to a
std::stringfails, it leaves the right hand operand in anunspecified state. (And if this is actually the code in the book, I’d
throw the book away.)
The simplest solution here is just to use a flag: