Check Value Inputted by User

◀ Alias For a Data Type▶ Const Pointer
Amazon In this chapter we’ll discuss how to check whether user inputs a numeric value from input stream. If a user inputs non-numeric characters, the program should reject it and prompt the user to try again.

There are several ways of doing it, and one of them is to get the entire line of input and see if it is a number of not. If so continue; if not prompt the user for a number again. Here is a complete sample program:
using namespace std;

int main() {
double number[3], tn; string ts; int i; cout<<"Enter 3 numbers.\n"; for(i=0;i<3;i++){ cout<<"Number "<<i+1<<": "; getline(cin,ts); if(ts=="0"){ number[i]=0; continue; } number[i]=atof(ts.c_str()); while(number[i]==0){ cout<<"Enter a number: "; getline(cin,ts); if(ts=="0"){ number[i]=0; break; } number[i]=atof(ts.c_str());
} } cout<<"You entered: "; for(i=0;i<3;i++) cout<<number[i]<<' '; cout<<endl; return 0; }
This program should be pretty straightforward. I use getline() to get the entire line of input from standard input, and then see if it’s zero or not. If so the number is determined to be zero. If not use atof() that <stdlib.h> provides to convert the string to a double.

Note that atof() returns 0 in two cases: the string contains the value 0; the string begins with a non-numeric character. To differentiate between these two cases, I examine the string to see if it’s “0”. However if the string is “0.0”, it will not pass the test and will be seen as non-numeric input. This is a disadvantage of using atof().

Also the string just needs to begin with a number for atof() to work. So “3.14abcdef~!@#” is converted to 3.14. These are the subtle points of handling the rejecting-non-numeric-input problem this way, but in general it does its job.

A better way is to rely on cin’s ability to tell good input from bad input. If you use cin>>number[i] as the while loop condition, then the condition is evaluated to true if user inputs a number (or a number appended by non-numeric characters); it is false if user inputs something that doesn’t begin with a digit.

In case of receiving a bad input, you need to use cin.clear() to reset input stream; without it, cin stops to read any further. Because bad input is still in the input stream, you need to get rid of it somehow.

You can use cin.get() to read one character by one character until you get a newline, which must be the last thing the user enters. After that you can prompt the user for a new input. By solving the problem this way, “0”, “0.0”, “0.000” are all recognized as 0.

Of course you can find other ways to deal with this problem. This is the heart of programming - creativity. There are almost always multiple ways of doing something. Your job is to figure out a good way of doing it.

Next let’s look at a confusing topic – const pointer!
◀ Alias For a Data Type▶ Const Pointer

Questions? Let me know!