c++ input validation

Dec 10, 2012 at 11:30am
am trying to do a calculator,but if instead of a number i put a letter i get an infinite loop.How can i avoid this?
Dec 10, 2012 at 11:42am
Store the input in a char, then check whether it's a number. (using ASCII, http://www.ascii-code.com/ , so if the ASCII code of the input is between 48 and 57, it's a number).
Dec 10, 2012 at 11:51am
thanks but am still a bit confused.
could you give me a very basic code example?
much appreciated.
Dec 10, 2012 at 11:55am
also my project is a calculator,certain input need to be negative and possitive,i just want a way for the user to not be able to input a word o letter or for the program to send the user a warning that letters are not allowed and then loop back to insert the figure again.
Dec 10, 2012 at 1:56pm
It's impossible to enter a letter if you're reading an integer, your input fails, and you are probably not checking for that error, which is why an infinite loop happens.

Try something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <limits>
int main()
{
    std::cout << "Enter a number\n";
    int n;
    while(! (std::cin >> n) )
    {
        std::cout << "That wasn't a number! Try again.\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    std::cout << "Thank you for entering the number " << n << '\n';
}
Dec 10, 2012 at 2:29pm
Thank you very much,very appreciated.
Dec 10, 2012 at 2:30pm
@Cubbi . u can try this instead of the numeric limits maybe? haha

1
2
3
4
5
6
7
8
9
10
11
cout << "Enter a number : ";
int n;
cin  >> n;

while( cin.fail() ){
       cin.clear();
       cin.ignore(100,'\n');
       cout << "Invalid input ! " << endl;
       cout << "Enter a number : ";
       cin  >> n;
}


because sometime nemuric limits are hard to memorize , while for exam. student might hard to rmb it. haha
Topic archived. No new replies allowed.