If I've got what you've asking right you want to allow a user to enter a number from a menu and have the corresponding action carried out. In pseudo code what you want is something like:
loop until doomsday
try and get an integer from a stream
if the stream hasn't failed
do something with the integer
otherwise if the stream is in a failed state from incorrect input
reset the stream
clear out the gash data that caused the stream to fail
"loop until doomsday" can be represented for stream style stuff as "loop until the stream is in a strange state".
while( std::cin )
will do that for the stream attached to
stdin
.
"try and get an integer from a stream" is just extracting an integer:
int number; std::cin >> number;
will do that for you.
Checking to see that the stream hasn't failed is similar to the loop control.
if( std::cin )
will do that for the same reasons.
Checking that the stream is in an invalid state is a bit harder. We can't just check that the stream has failed, we have to check that it's not failed because of an end of file condition or because the underlying stream buffer has screwed up. We can do this with the following test:
if( std::cin.fail() && !std::cin.bad() && !std::cin.eof() )
Clearing the error on the stream is easy:
std::cin.clear()
will do that. We can get rid of the input that was entered incorrectly by reading it into a string and discarding it:
std::string junk; std::getline( std::cin, junk );
Putting it all together we get:
#include <iostream>
#include <string>
int main()
{
while( std::cin )
{
int number; std::cin >> number;
if( std::cin )
{
std::cout << "You entered: " << number << std::endl;
}
else
{
if( !std::cin.eof() && !std::cin.bad() && std::cin.fail() )
{
std::cout << "You didn't enter a number" << std::endl;
std::cin.clear();
std::string junk;
std::getline( std::cin, junk );
}
}
}
}
You can simplify that to taste and insert your own code to taste. If you compile and run the code above it'll echo any integers you input to
stdout
and reject any other input. To exit the program use CTRL-Z on windows or CTRL-D on unixy systems. Note that it won't handle all error conditions (enter a number with a decimal point and see) but you can tighten the code up to handle that as well.
To really understand streams I'd recommend buying, reading and inwardly digesting
Standard IOStreams and Locales by Klause Kreft and Angelika Langer. It's really good coverage of "how do I do stuff with streams..."