Search code examples
c++stringint

How to check is string correct to convert it to int?


Now I talk only about stl functions. Not something like this:

for (char c : s) {
  if (c < '0' || c > '9') {
    return false;
  }
}

Solution

  • I don't believe there is a built in function that does this, but you can use an algorithm to do this:

    bool is_valid_int(const std::string& s)
    {
        return std::all_of(std::begin(s), std::end(s), 
                             [](unsigned char c) { 
                               return std::isdigit(c); 
                           });
    }
    

    Note that this solution only checks if all the characters of a string are digits. To check whether it's convertible to an int, you could do something like:

    int n;
    try { n = std::stoi(s); }
    catch(...) { /* do something */ }