Reputation: 73
Say i have something like this int s
and cin >> s
. Is there a simple way to test if user input for 's' is a white space without resorting to isspace
which would result in first converting that int to a string and then back to an int again after my test.
Upvotes: 0
Views: 2078
Reputation: 10733
If you do:-
int s;
cin >> s;
It won't even return on entering whitespace. User has to enter some non-whitespace character.
Upvotes: 1
Reputation: 27528
Use the std::getline
function to get a whole line of input as a std::string
, then parse the line, which can be as easy as using std::stoi
in C++11:
std::string input;
std::getline(input, input, std::cin);
int const s = std::stoi(input);
It will check the input for validity and throw an exception if no conversion can be performed. Additionally, having the input available as a std::string
, you can perform any checking you like, and it's trivial to check the existence of a particular character in a string.
Upvotes: 3