Error Checking / Input Validation In C++ (Double)

Error Checking / Input Validation In C++ (Double) will show you how to validate user input and error check for a double in C++. I hope this deems helpful to you!

The control structures and functions used within this program include a while loop and the .clear() and .ignore() functions.

1. Create A Variable

To begin with, inside of the int main() function, create a variable that will store user input.

double num;

2. Ask User For Decimal Number

Then, ask the user to enter a decimal number.

cout << "Enter a decimal number: ";

3. Receive User Input

Next, we need to receive the users input into the num variable. However, in order to input validate we must place the cin >> num; within the test expression of a while loop.

while (!(cin >> num))
{

}

Make sure to wrap the cin >> num; between two parentisis () and use the ! symbol. Otherwise the program will accept all other data types except floating point. So, watch out!

4. Explain, Clear, and Discard Previous Input

Now, within the while loop, if the user’s input is anything other than an double, we will need to explain the error, clear the input stream, and discard previous input.

while (!(cin >> num))
{
    // Explain error
    cout << "ERROR: a number must be entered: ";

    // Clear input stream
    cin.clear();

    // Discard previous input
    cin.ignore(123, '\n');
}

It is important to mention here that the .ignore() function takes two arguments–The first being an integer that tells the program to skip the next 123 characters up until new line character ('\n')–the second argument. Remember, if neither the .clear() function nor the .ignore() function are used, then the program will leave user guessing what to do next after entering a number. And that’s not good. So pay attention here.

5. Display Input & Salutation

Finally, after the user’s input is validated, display the decimal number, say good bye, and end the program.

// Display the number the user has entered
cout << "Your decimal number is: " << num << endl;
    
// Salutation
cout << "Thanks. Bye." << endl;

return 0;

6. That’s it for Error Checking / Input Validation In C++ (Double)

To view FULL CODE, refer to this GitHub repository. Otherwise, thank you for taking interest in this post.

  • Jesús Hilario H.

Leave a Reply