Question

Is there an effective way in C to check if a given string is convertable to an integer?
An output error should indicate if the string is convertable or not.
For example, "aa" is not convertable, "123" is convertable.

Was it helpful?

Solution

C++11 has the std::stoi, std::stol, and std::stoll functions, which throw an exception if the string cannot be converted.

OTHER TIPS

With C, use the strtol(3) function with an end pointer:

 char* end=NULL;
 long l = strtol(cstr, &end, 0);
 if (end >= cstr && *end)
    badnumber = true;
 else
    badnumber = false;

With C++11, use the std::strtol function (it raises an exception on failure).

You could also loop through the string and appply isdigit function to each character

bool is_convertible_to_int(const std::string &s) {
  try {
    int t = std::stoi(s);
    return std::to_string(t).length() == s.length();
  }
  catch (std::invalid_argument) {
    return false;
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top