0

I wont to check whether the age is number or not in this example it will accept 1E as number while it will not accept E1, I wont to accept only digit
not any symbol or alphabet

 int main()
    {
      int age= 0;
        std::cin >> age; 
        if (std::cin.fail())
        {
        std::cout << "I failed, try again ..." << std::endl;
        std::cin.clear(); // reset the failed state
    }
  • `getline` + `regex` – knivil Feb 27 '17 at 14:29
  • @knivil, If trying to store the integer result, regex is kind of overkill. A call to `std::stoi` is enough with proper error checking. – chris Feb 27 '17 at 14:31
  • @knivil Using `regex` is probably overkill. – πάντα ῥεῖ Feb 27 '17 at 14:31
  • 1
    Read a line from `std::cin` into a `std::string` (e.g. using `std::getline()`. Then check the string by whatever criteria you choose to determine if it contains a number. If it does, extract the number from the string (e.g. using a `std::istrstream` to help). – Peter Feb 27 '17 at 14:31
  • If you want to verify the entire line of input, you will have to read a string with `getline` and check the content. The input `1E` is valid if your next statement is `cin >> ch;`. That would get you `1` in `age` and `'E'` in `ch`. – Bo Persson Feb 27 '17 at 14:31
  • Not exactly the same question but this answer may be of help: https://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it/27004240#27004240 – Galik Feb 27 '17 at 14:34
  • Nobody should throw an exception on verifying user input. And `std::stoi("31337 with words") is 31337` is not the thing I would suggest here. – knivil Feb 27 '17 at 14:42

1 Answers1

0

Really cin and the extraction operators are no good for parsing user input. They're OK for inputting automatically formatted records, but not input that is likely to have free form errors in it.

If you use line-based input, then call the function strtol(), you can find digits. strtol() also handles minus signs and numbers which are too large to fit into an integer. It's essentially the safe integer parser. Also, on error, you can easily discard the whole line and ask the user to re-enter, which is usually the desired behaviour.

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18