简体   繁体   中英

Error checking cin.fail() for a string variable in C++

#include <iostream>
using namespace std;

int main()
{
  int i;
  cout << "Enter: " << endl;
  cin >> i;

  cout << cin.fail() << endl;
}

This is my typical implementation for error checking to make sure I am entering a valid input and this was what I was taught. The problem with my above code is if I type in '4d' it stores the 4 in variable 'i', but leaves the 'd' in the buffer, so the cin.fail() test returns false, but I want it to return true. If I type in 'c' or 'ccc' etc... cin.fail() returns true as I want.

Is there any proper command to test for what I have described?

I suspect there are more than one ways to solve your problem. I can think of the following two.

  1. Get the next character right after you read i . If that character is not a whitespace character, you can flag that as an error.

     cin >> i; if ( cin ) // reading to i was successful. { int c = cin.get(); if (!isspace(c) ) { // There was a non whitespace character right // after the number. // Treat it as a problem } }
  2. Read a token of characters and check whether any of them is not a digit.

     std::string token; cin >> token; for ( auto c : token ) { if (!isdigit(c) ) { // Problem } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM