I've been searching (on the internet, in books, anywhere) for a solution to my problem for some time and I can't seem to find it. I think there are plenty of posts about this subject, I just haven't found the right one I think and I think I never will, so I'm going to ask it myself.
At a certain point in a program that I'm writing, I need to get user input, as a positive integer. When the user puts in something different than an integer (or a negative integer), the program will respond with "Invalid input.". When the user types in an correct integers, it will continue doing what it has to do (in this case it will 'cout' the input). This is all going well, but things go wrong when the user types in:
"1a" (a number combined with a character), it will only recognize "1";
"1 2" (number space number), it will only recognize "1";
"1,2" (number comma/dot number), it will only recognize "1";
I'd like to get the "Invalid input."-output in all cases.
I'll post a simplified version of my code to show you what I've got so far and to ask you guys if you could provide me with a solution for this problem.
Thanks in advance!
#include <iostream>
using namespace std;
int main()
{
int input;
cout << "Enter a number higher than 0: ";
cin >> input;
while (cin.fail() || input < 1)
{
cout << "Invalid input.\nPlease enter a (positive integer) number higher than 0: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin >> input;
}
cout << "Your input is: " << input << endl;
return 0;
}