Hi,
There was an issue about cin.ignore() method some time ago in this forum, but the thread is closed now. At the time, the question was so vague that the response was to read cin.ignore method reference page.
I have done, and to me is clear that, if I want to get rid off of the next character in cin buffer, I just have to do
cin.ignore (1) // or any other number for more chars in buffer
even if the next character in buffer is '\n' because the default delimiter is EOF as it's said in reference.
With this in mind I don't know why this code is not working at all. It gets the program into an infinite loop. Where is the problem?.
The idea is to make a function to safely asks the user for an integer if he or
she enters a letter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
int ask_for_integer_value (string prompt)
{
int value = 0;
bool keep_asking = true;
cout << prompt;
do
{
cin >> value;
if (cin.fail ())
{
cout << "Input error. Please try again: \n";
// Next, in ignore, I've tried with 1, 256, etc. This is the last
//dramatic try. Also with other delimiters (second parameter no put in
//last try. Simply, it looks that it's not working at all.
cin.ignore(std::numeric_limits<std::streamsize>::max());
cin.clear ();
}
else
keep_asking = false;
} while (keep_asking);
return value;
} // end of asf_for_integer_value
|
Searching in the page I've found this code that solves my problem, but I think
my version its cleaner, given it works. Anyway, I feel curious about what I'm doing wrong to make cin.ignore() not working.
1 2 3 4 5 6 7 8 9 10 11 12
|
string input = "";
do
{
cout << "Please enter a valid number: ";
getline(cin, input);
// This code converts from string to number safely.
stringstream myStream(input);
if (myStream >> valor)
break;
cout << "Invalid number, please try again" << endl;
} while (true);
|
As always, thanks for your help and for the page. I use it almost every day.
Fernando