0

Hy,

I want to read a number in c++ with the cin function. I know there are a lot of threads but I didn't found a perfekt solution.

First I tried it with cin.fail() function. But if I input a number like this 12asdf it reads the 12 correct and didn't throw an error.

Then I tried to read a string and convert it with the atoi() function but if I read a string like this 12asdf I have the same problem. It reads the 12 correct and throws no error.

The I tried it with the function but the all_of function isn't available in visual 2013.

if ( std::all_of(input.begin(), input.end(), std::isdigit) )
{
     //input is integer
}

How can I check an input like this 12asdf and throw an error?

Best regards

user2644964
  • 763
  • 2
  • 10
  • 28

1 Answers1

2

You can use the following function:

bool is_number(const std::string& s) {
  return !s.empty() && std::find_if(s.begin(),
    s.end(), [](char c) { return !std::isdigit(c); }) == s.end();
}

and then use it like below:

  std::string num;
  std::cout << "Enter number: ";
  std::getline(std::cin, num);
  while (!is_number(num)) {
    std::cout << "Input is not a number , enter again: ";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    num.clear();
    std::getline(std::cin, num);
  }
101010
  • 41,839
  • 11
  • 94
  • 168
  • Calling [`std::isdigit`](https://en.cppreference.com/w/cpp/string/byte/isdigit) with a negative argument will cause undefined behavior (unless that value happens to be `EOF`). Therefore, `std::isdigit(c)` should be changed to `std::isdigit(static_cast(c))`. See [this answer](https://stackoverflow.com/a/45007070/12149471) to another question for the reason behind this. – Andreas Wenzel Sep 22 '21 at 01:10