How do you do it?

My program asks a user to input any number of gallons to be converted into liters.

Now how do you tell the user that he/she is stupid when the users enters something else like a letter or such?

Thanks.
Get input.
Verify input.
If input is a number, break
Else print "Enter a number, please" and reiterate with continue statement.

Like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
do {
    std::cout << "Enter a number: ";
    getline(std::cin, str);
    std::cout << "\n";
    n = atof(str); // n is an integer, str is an std::string. If str can be converted to a number successfully, then you can use n
    if (n) { // Check str is a number
        break;
    } else {
        std::cout << "\t";
        continue;
    }

} while (true);
Last edited on
Here is an article on input validation by Zaita:
http://www.cplusplus.com/forum/articles/6046/
Very odd code chris, a couple things about it.

1. atof is not standard C++, it's deprecated, it's dangerous, it's just not a good choice.
2. even if you were to use one of those functions, it should be atoi since you specified an int.
3. again, even if you were to use atof or atoi, they cannot accept a string as a parameter. These are C functions, afterall. The correct parameter would be str.c_str()
4. your code would claim that the number 0 is not a number.
5. this code would say that a combination of numbers and letters is a valid number (if the first character was a number)
6. this may just be a style choice, I guess, but infinite loops like that are infuriating.



Anyway, good post there by Zaita, check that out.
Last edited on
In addition to Tevsky's post, even atoi for that matter is not safe, as it returns 0 on failure which is a valid int. Better way is sstream lib.
Sorry, I wasn't thinking.
I keep on putting atof() instead of atio() by accident too :l
Anyway, the code is bad but the principle is the same I guess.
But Zaita's post is definitely better.
Got it. Thanks
Topic archived. No new replies allowed.