1
#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?

5
  • 1
    read it as a string then use isdigit() to check Commented Mar 16, 2016 at 5:06
  • Thanks for the reply. I'm actually doing this as a homework assignment for a class, and we are not annoyed to use things we haven't learned (we haven't gone over isdigit()). Our instructor just wanted us to perform error testing, but didn't mention how in depth. Is there any way to do this with cin.fail()? Commented Mar 16, 2016 at 5:16
  • 1
    while(cin << i) { if(cin.fail()) cout << "Failed" << endl; } Commented Mar 16, 2016 at 5:22
  • you mean cin >> i, right? Commented Mar 16, 2016 at 5:31
  • you are right. sorry for mistype Commented Mar 16, 2016 at 5:32

1 Answer 1

1

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
       }
    }
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.