Answer the question
In order to leave comments, you need to log in
How to perform input validation in C++?
There are a certain number of programming laboratories at the university, each of them has a requirement: verification of input data. I compile in MinGW Develover Studio, I / O is made through the console. Is there any elegant way to check input if, for example, the user enters letters/characters while the input is made into an int variable? The compiler does not react to such things, does not change the variable, displays either the old integer value or garbage from memory.
Answer the question
In order to leave comments, you need to log in
There are a lot of possibilities to check:
1. Save to a string and then check, then use atoi
2. Use scanf, above
3.
try/catch, above
4. cin
and it can be scolded, but in terms of code volume it is the largest.
2nd and 4th are convenient for simplicity, but you never know if the user entered 0 or just a set of characters.
3rd apparently meant cin, but in order for exceptions to work, they must be enabled for this thread cin.exceptions(ios::failbit);
➜ /tmp cat test.cpp
#include <iostream>
int main(int argc, char *argv[])
{
int i;
std::cin >> i;
if (!std::cin) {
std::cout << "bad integer" << std::endl;
}
return 0;
}
➜ /tmp g++ test.cpp
➜ /tmp ./a.out
1234
➜ /tmp ./a.out
adsf
bad integer
I/O is done through the console. Is there any elegant way to validate input if for example user enters letters/characters
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question