Reputation: 797
This is what the piece of code below is supposed to do. It's supposed to read the info in the stream (called lineStream) that has been inputted by the user into an int. The data is either supposed to be a single number or the word "all". If it's neither I'm supposed to inform the user it's an error.
This is what happens though: when the user enters a number everything works out fine. When he enters the word "all" though, the stream fails (as expected since I'm reading it into an int). When this happens I try reading the info in the stream into a string ("stringstream") and checking if the user has entered "all". However, even when the user has entered "all", the stream only outputs "" (empty string) when I try to read from it after it fails. Does anyone know why? Thanks.
int nameofnode;
lineStream >> nameofnode;
if (lineStream.fail())
{
string streamString;
lineStream >> streamString;
if (streamString == "all") {
if (lineStream.peek() != EOF) { //Too many arguments
cout << "Error: too many arguments\n";
return;
}
cout << "Print: all nodes\n";
}
else
{
cout << "Error: Invalid argument";
}
return;
}
Upvotes: 1
Views: 293
Reputation: 66194
Once in a fail-state, there is next-to-nothing you can do with an iostream without clearing the fail state one way or another. In this case..
int nameofnode;
if (!(lineStream >> nameofnode))
{
lineStream.clear(); // <<==== HERE
string streamString;
if (lineStream >> streamString && streamString == "all") {
if (lineStream.peek() != EOF) { //Too many arguments
cout << "Error: too many arguments\n";
return;
}
cout << "Print: all nodes\n";
}
else
{
cout << "Error: Invalid argument";
}
return;
}
Upvotes: 2