I was recently reading a C++ textbook (Accelerated C++) and the author wants to read input data of the form:
name1 double double double double ...
name2 double double double double ...
^ all doubles from here on out will go into a vector
The author's idea is to do do something like read from cin until the stream fails, which it will do either because the input is finished, or because we try reading name2 as a double which will put the stream into a fail state. In regards to this he says
In either case, then, we would like to pretend that we never saw whatever followed the last homework grade. Such pretense turns out to be easy: if we encountered something that wasn't a grade, the library will have left it unread for the next input attempt. Therefore all we need to do is tell the library to disregard whatever condition caused the input attempt to fail, be it eof or invalid input.
My question relates to the bolded part. The author seems to be implying that a failed attempt at reading from cin will not discard the token that it failed on, but rather leave it in the stream. However, I wrote a program to test this and this does't seem to be the case:
Input data:
p1 90 91 92 93 94
p2 81 82 83 84 85
Program:
using std::cout; using std::cin;
using std::endl; using std::string;
int main() {
while(cin) {
string name, midterm, final;
cin >> name >> midterm >> final;
double x;
cout << endl << "Name: " << name
<< ", Mid: " << midterm
<< ", Final: " << final << "\t"
<< "Homework: {";
while(cin >> x) {
std::cout << x << ", ";
}
cout << "}" << endl;
if(cin.fail()) {
cin.clear();
string f;
cin >> f;
cout << "Stream failed - next token: " << f << endl;
}
}
}
Aucun commentaire:
Enregistrer un commentaire