validation

hi, I am just learning C++ ATM, but have programmed in other languages with moderate amounts of success (java, c#).

I am trying to validate input (cin) to an integer, but I want to refuse any non integer. unlike most other higher level (lazier I guess) languages c++ will somehow go about putting any value into an int; which cause all sort of problems.

what I want to do check the string to make sure it is an integer than parse it into an int.

this must be a common task surely, so there must be a function (that returns a bool? isInt - something like that), or at least what is the common way to do it. The best way I can think of would be to extract cin to char[] (or pointer***), then compare each element again '1', '2', '3'... then if all is well then parse. but there must a be a more elegant way. (like c#'s tryParse)


***secondary question 'bout pointers; when should I use them over arrays. (or am i viewing them wrong). Also when i make an istance of a class, which is better practice. (or when would you use each; bare in mind that all this was done for me in C# & java)

to make a pointer:
myclass *mcp = new myclass("constructor")
mc->method();

or (is this an object then?)

myclass mpv("constructor");
mpv.method();

thanks for you time.
Last edited on
Simple but bad version:
1
2
3
int n;
if (!(std::cin >>n))
     //not a number 

Complicated but good version:
1
2
3
4
5
6
7
8
int n;
{
    std::string input;
    std::getline(std::cin,input);
    std::stringstream stream(input);
    if (!(stream >>n))
        //not a number
}
Don't forget about extra junk that may be at the end of the number:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int n;
// Instruct the user
std::cout << "Please enter an integer value> " << std::flush;
while (true)
{
    // Get the user's input
    std::string input;
    std::getline(std::cin,input);
    // Trim any trailing whitespace
    input.erase(input.find_last_not_of(" \t")+1);
    // Convert it to a number
    std::istringstream stream(input);
    stream >> n;
    // Was conversion successful without any leftovers?
    if (stream.eof()) break;
    // Re-instruct the user
    std::cout << "You must enter an INTEGER value> " << std::flush;
}
std::cout << "Good job! You entered the number \"" << n << "\".\n";


Oh yeah, almost forgot.
http://www.cplusplus.com/forum/beginner/13044/page1.html#msg62827
Last edited on
Doesn't operator>>() ignore whitespace?
I think Duoas was meaning whitespace and other characters after the number.
I'm pretty sure it ignores those, too. It's why you can't use >> to get sentences from std::cin.
It doesn't, otherwise you would get whole sentences from cin.

e.g.:

"argle argle"
cin >> something
something = "argle"
buffer = " argle"
Try the following, non-numeric input:

99bottles-of-beer

8 bananas
Last edited on
Oh, I get it now. But I think it would be better if the program tried its best to make sense of the input.
Topic archived. No new replies allowed.