Rulli Smith
Rulli Smith

Reputation: 353

C++ check input value with while loop

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;
}

Upvotes: 1

Views: 2756

Answers (2)

Tejendra
Tejendra

Reputation: 1934

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++?

Upvotes: 2

David
David

Reputation: 13

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.

Upvotes: 0

Related Questions