S
S
Sergey Sokolov2014-02-27 20:02:26
C++ / C#
Sergey Sokolov, 2014-02-27 20:02:26

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

4 answer(s)
A
AxisPod, 2014-02-28
@freaks

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

X
xandox, 2014-02-28
@xandox

➜  /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

J
jcmvbkbc, 2014-02-28
@jcmvbkbc

I/O is done through the console. Is there any elegant way to validate input if for example user enters letters/characters

You would also say, input-output through the keyboard and monitor.
If you use scanf , then it returns how many fields are actually scanned.
Those. scanf("%d", &i) will return 0 if you enter letters.

O
OnYourLips, 2014-02-27
@OnYourLips

try/catch?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question