1

I have the following problem. I try to check the format of the input value with the while loop. If the input is wrong, I want to get back and ask the user to give a new input. But this step is just skipped and it continues with the rest of the code. How can I fix it? Thanks in advance! P.S.: Credits is a double.

cout << "Enter amount of credits: "; 
cin >> credits;
while(cin.fail()){
    cout<<"Wrong input! Please enter your number again: ";
    cin>> credits;
}
6

2 Answers 2

2

You can validate the data type of input provided in a very simple way

cout << "Enter amount of credits: "; 
while(!(cin>> credits)){
    cout<<"Wrong input! Please enter your number again: ";
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

ignore is necessary to clear the standard input, as mentioned in reference below since operator>> won't extract any data from the stream anymore as it is in a wrong format

For more reference you can check

  1. c++, how to verify is the data input is of the correct datatype
  2. how do I validate user input as a double in C++?
Sign up to request clarification or add additional context in comments.

Comments

0

Your original code works with this modification:

while (std::cin.fail())
{
    std::cout << "Wrong input! Please enter your number again: ";
    std::cin.clear();
    std::cin.ignore();
    std::cin >> credits;
}

As Tejendra mentioned, cin.clear and cin.ignore is the key.

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.