Preventing Implicit Conversion in C ++

I am asking the user for integer input, and I do not want to execute the code if it is not a strictly integer.

int x; if(cin >> x) 

For example, if the user enters double above, the if statement will be executed with an implicit conversion to an integer. Instead, I do not want the code to run at all.

How can I prevent this?

+4
c ++
source share
2 answers

There is no conversion. If the user enters a fraction (no double ), then extraction >> stops at the decimal point.

http://ideone.com/azdOrO

 int main() { int x; std::cin >> x; std::cout << std::cin.rdbuf(); } input: 123.456 output: .456 

If you want to mark the presence of a decimal point as an error, you will need to do something to extract it from cin and detect it.

One good parsing strategy with C ++ streams is getline , which you know you will handle in istringstream , name it s , and then make sure it is s.peek() == std::char_traits<char>::eof() when you're done. If you are not using getline to get the individual number, peek can check if the next character is a space (using std::isspace ) without consuming that character from the stream.

Probably the cleanest way to verify that input is complete, although it is somewhat esoteric, is to use std::istream::sentry .

 if ( ! ( std::cin >> x ) || std::istream::sentry( std::cin ) ) { std::cerr << "Invalid or excessive input.\n"; } 

This takes up space at the end of input. sentry also provides the noskipws option to avoid space usage.

 if ( ! ( std::cin >> x ) || std::istream::sentry( std::cin, true ) ) { std::cerr << "Invalid or excessive input. (No space allowed at end!)\n"; } 
+9
source share

It seems to work. He ignores the spaces, I do not know if this is good with you.

 string s; cin >> s; stringstream ss(s); int x; if (! (ss >> x)) { cerr << "You didn't enter an integer." << endl; return -1; } string temp; ss >> temp; if (! temp.empty()) { cerr << "You didn't enter an integer." << endl; return -1; } 
0
source share

All Articles