How to Do Input Validation in C++ with Cin

Good input validation loop using cin - C++

I'm not a huge fan of turning on exceptions for iostreams. I/O errors aren't exceptional enough, in that errors are often very likely. I prefer only to use exceptions for less frequent error conditions.

The code isn't bad, but skipping 80 characters is a bit arbitrary, and the error variable isn't necessary if you fiddle with the loop (and should be bool if you keep it). You can put the read from cin directly into an if, which is perhaps more of a Perl idiom.

Here's my take:

int taxableIncome;

for (;;) {
cout << "Please enter in your taxable income: ";
if (cin >> taxableIncome) {
break;
} else {
cout << "Please enter a valid integer" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}

Apart from only skipping 80 characters, these are only minor quibbles, and are more a matter of preferred style.

What is the best way to do input validation in C++ with cin?

Here is code you could use to make sure you also reject things like

42crap

Where non-number characters follow the number. If you read the whole line and then parse it and execute actions appropriately it will possibly require you to change the way your program works. If your program read your number from different places until now, you then have to put one central place that parses one line of input, and decides on the action. But maybe that's a good thing too - so you could increase the readability of the code that way by having things separated: Input - Processing - Output

Anyway, here is how you can reject the number-non-number of above. Read a line into a string, then parse it with a stringstream:

std::string getline() {
std::string str;
std::getline(std::cin, str);
return str;
}

int choice;
std::istringstream iss(getline());
iss >> choice >> std::ws;
if(iss.fail() || !iss.eof()) {
// handle failure
}

It eats all trailing whitespace. When it hits the end-of-file of the stringstream while reading the integer or trailing whitespace, then it sets the eof-bit, and we check that. If it failed to read any integer in the first place, then the fail or bad bit will have been set.

Earlier versions of this answer used std::cin directly - but std::ws won't work well together with std::cin connected to a terminal (it will block instead waiting for the user to input something), so we use a stringstream for reading the integer.


Answering some of your questions:

Question: 1. Using a try catch block. It didn't work. I think this is because an exception is not raised due to bad input.

Answer: Well, you can tell the stream to throw exceptions when you read something. You use the istream::exceptions function, which you tell for which kind of error you want to have an exception thrown:

iss.exceptions(ios_base::failbit);

I did never use it. If you do that on std::cin, you will have to remember to restore the flags for other readers that rely on it not throwing. Finding it way easier to just use the functions fail, bad to ask for the state of the stream.

Question: 2. I tried if(!cin){ //Do Something } which didn't work either. I haven't yet figured this one out.

Answer: That could come from the fact that you gave it something like "42crap". For the stream, that is completely valid input when doing an extraction into an integer.

Question: 3. Thirdly, I tried inputting a fixed length string and then parsing it. I would use atoi(). Is this standards compliant and portable? Should I write my own parsing function?

Answer: atoi is Standard Compliant. But it's not good when you want to check for errors. There is no error checking, done by it as opposed to other functions. If you have a string and want to check whether it contains a number, then do it like in the initial code above.

There are C-like functions that can read directly from a C-string. They exist to allow interaction with old, legacy code and writing fast performing code. One should avoid them in programs because they work rather low-level and require using raw naked pointers. By their very nature, they can't be enhanced to work with user defined types either. Specifically, this talks about the function "strtol" (string-to-long) which is basically atoi with error checking and capability to work with other bases (hex for example).

Question: 4. If I write a class that uses cin, but dynamically do this kind of error detection, perhaps by determining the type of the input variable at runtime, will it have too much overhead? Is it even possible?

Answer: Generally, you don't need to care too much about overhead here (if you mean runtime-overhead). But it depends specifically on where you use that class. That question will be very important if you are writing a high performance system that processes input and needs to have high throughout. But if you need to read input from a terminal or a file, you already see what this comes down to: Waiting for the user to input something takes really so long, you don't need to watch runtime costs at this point anymore on this scale.

If you mean code overhead - well it depends on how the code is implemented. You would need to scan your string that you read - whether it contains a number or not, whether some arbitrary string. Depending on what you want to scan (maybe you have a "date" input, or a "time" input format too. Look into boost.date_time for that), your code can become arbitrarily complex. For simple things like classifying between number or not, I think you can get away with small amount of code.

Validating user input using cin

The problem is that you are testing the value of *(temperatures + i * days + j) even when the input has failed. Plus you are using ignore incorrectly (only ignoring one character instead of all outstanding characters). Plus you have overly complex code

Here's a better version

#include <limits> // for std::numeric_limits

cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
int temp;
while (!(cin >> temp) || temp < -50 || temp > 50)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
}
temperatures[i * days + j] = temp;

I used a new variable temp to simplify the code. I included cin >> temp in the while loop condition thereby only checking temp if the input has succeeded, and I used cin.ignore(numeric_limits<streamsize>::max(), '\n'); to ignore all characters remaining in the input.

Note this probably isn't perfect. If you entered say 10deg then the input would succeed (temp would equal 10) even though the input has non-digits in it. If you want to do input validation properly then the only real way is to read the input as a string, and test the string, before converting to an integer.

C++ Input Validation

Test for cin.fail first, and print the message once, then process and clear off the characters in the loop. This will account for e.g. people typing in "bbb" which will trigger three runs through the loop, but it will only give you the message one time:

    if (cin.fail())
{
cout << "Enter only an integer please." << endl;
}
//data type validation
while (cin.fail())
{
cin.clear();
cin.ignore();
cin >> choice;
}

You can also move the instructions/input validation code to the top of the while loop, then you don't need to have it repeated outside the while loop to start with

C++ User input validation not working properly

bool has_only_digits(string s){
return s.find_first_not_of( "0123456789" ) == string::npos;}

This method is the simplest way I found to check if a string contains a number. So if it returns true the string has only digits else it contains more than just digits.

If the statement is false you can then clear the cin like you have done above.

Validating integer input from user in c++

You need to use cin.clear() and cin.ignore when cin is in an error state, change your inputAge() function to this:

    void inputAge() {
try {
cout<<"Enter age: ";
cin>>age;
if(cin.fail()) {
cin.clear(); //YOU MUST CLEAR THE ERROR STATE
cin.ignore();
throw "invalid";
}
else {
if(age < 18 || age > 55) {
MyException e;
e.setError("User has age between 18 and 55 ");
throw e;
}
}
}catch(MyException &e) {
cout<<e.what()<<endl;
inputAge();
}
catch(const char* msg) {
cout<<msg;
inputAge();
}
}

When std::cin is in an error state, you must clear it before reusing it. Please see this post on cin.fail() and cin.ignore()

Inputting char and int in int variable using cin in C++

Welcome to Stack firstly. Try this

#include <iostream>
#include <string>

int main() {

std::string theInput;
int inputAsInt;

std::getline(std::cin, theInput);

while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {

std::cout << "Error" << std::endl;

if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}

std::getline(std::cin, theInput);
}

std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}

I made an output to visualize it. The variable "inputAsInt" would be the one you have to further work with.



Related Topics



Leave a reply



Submit