dasfex
dasfex

Reputation: 1260

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;
  }
}

Upvotes: 0

Views: 603

Answers (2)

M.M
M.M

Reputation: 141554

You can convert with strtol and then check if the whole string was consumed, e.g.:

bool string_is_valid(std::string s)
{
    char const *startptr = s.c_str();
    char *endptr;
    strtol(startptr, &endptr, 10);

    return endptr - startptr == s.size();
}

The endptr is always set whether or not conversion succeeds.

If it is important to distinguish values that are correct for long but out of range for int then you would need to store the return value of strtol and test it against INT_MAX and INT_MIN.

This option differs from std::stoi in that the latter does not give any information about whether there were other trailing characters after a valid number (e.g. 3x and 3 both would return 3).

Upvotes: 0

cigien
cigien

Reputation: 60208

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 */ }

Upvotes: 2

Related Questions