Validating keyboard input

May 26, 2010 at 18:37:40
Specs: Windows 7 Professional (32-bit), 3GB 2.0GHz Dual core CPU
I am learning basic Windows console c++.
What is the best way to validate user input in a console program? Is there a function like scanf I could use? I do not know the syntax.
What I want to do:
Program asks user to enter an integer value, e,g, 5
Use cin >> to read character
Then check to see if the input is an integer - a number. If it is not, ignore the input and ask to re-enter until the input is a valid number.
I know about if statements, such as if ( num1 < 50 )
error goes here
but I want to make the program check to see if it is an integer. When I enter any other input, e.g. aaa or b or x4g etc, the program loops the output until I stop it. What is the best way to make a function to check this?

See More: Validating keyboard input

Report •

May 26, 2010 at 20:00:03
I don't know it well enough to give an example, but C++ has the stringstream class, which is quite similar to using sscanf

#include <sstream>

imo, the best way to avoid potential stream errors is not to provide an opportunity to create the chance... always read in numeric data using a string and then convert it.

For example, with a bit of C

char nbuf[10] = { 0 };
int num;

do {
   std::cout << "Enter a number: ";
   std::cin >> nbuf;
} while((sscanf(nbuf, "%d", &num)) != 1);


Report •
Related Solutions

Ask Question