0

I have looked everywhere but I can't seem to find and implement an input validation that only takes in integers, I have my code running perfectly fine but my only problem is that since ive added my validation code, it requires the user to enter twice before it accepts the second input, all I want is for the user to only have to enter in once with good validation so the program recognizes its not a int and displays the appropriate message, id be very appreciative of any help!

Here's my code:

cout<<"Please enter your first value: \n";
cin>>a;

//Error checker to check if input is a number
while(!(cin >> a))
{    
    cin.clear();
    std::cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Invalid input. Please Try again: "<<endl;
}
1
  • 3
    Skip the first input, i.e. the single cin>>a line? Commented Apr 19, 2013 at 23:52

1 Answer 1

1

You are trying to do cin>>a once before the while loop and then again in the while loop condition. Just remove the initial extraction.

cout<<"Please enter your first value: \n";
// cin>>a; <- remove this

//Error checker to check if input is a number
while(!(cin >> a))
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.