Im making a game and i cant seem to figure out how to get the input to keep letting me input if the user enters something wrong it just infinitly loops, i have tried while loops, do while loops everything and i cant get it to work.
actually i have a question, i tried this exact thing except i didnt have numeric_limits<streamsize>::max() in ignore(), i had (500, '\n') why didnt it work then?
#include <iostream>
#include <string>
#include <limits>
usingnamespace std;
int main()
{
cout << "Please, enter a number\n";
int n = 0;
while( !(cin >> n) )
{
cout << "You need to enter a number\n";
cin.clear(); // reset the error flags
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Thank you for entering the number " << n << '\n';
return 0;
}
is that it will accept strings which begin with a number but then continue with other characters, e.g.
Please, enter a number
42nd Street
Thank you for entering the number 42
and
Please, enter a number
99 red balloons
Thank you for entering the number 99
If you want just a number, you need something more like this [1]
#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
int main()
{
cout << "Please, enter a number\n";
int n = 0;
bool notDone = true;
while (notDone)
{
std::string line;
std::getline(std::cin, line);
std::istringstream is(line);
char dummy;
if (!(is >> n) || (is >> std::ws && is.get(dummy)))
std::cout << "You need to enter just a number\n";
else
notDone = false ;
}
cout << "Thank you for entering the number " << n << '\n';
return 0;
}
Please, enter a number
99 red balloons
You need to enter just a number
99
Thank you for entering the number 99
Andy
[1] A basic take off of cire's templated function here:
"actually i have a question, i tried this exact thing except i didnt have numeric_limits<streamsize>::max() in ignore(), i had (500, '\n') why didnt it work then?"
In many situations, there would be no discernible difference between the use of numeric_limits<streamsize>::max() instead of 500.
It is simply that the former is a complete solution which should always work (by ignoring an unlimited number of characters) while the latter would fail if the user had typed in more than 500 characters before pressing enter.
hmm, so i guess numeric_limits<streamsize>::max() is the better solution then. is there any problem with using it all the time? also how do i see whats left in the input buffer? and lastly, how can i create a simple input buffer?