1

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.

Deanie
  • 2,205
  • 2
  • 17
  • 32
The_Mundane
  • 97
  • 1
  • 1
  • 9
  • 1
    It is probably best to ask two separate questions for this - the best answers for each language are likely very different (although there will be a lot of overlap in people qualified to answer). – BoBTFish Apr 23 '14 at 07:41
  • Does "123aa" is convertible to integer for you ? – Jarod42 Apr 23 '14 at 07:42
  • "123aa" is not convertable to an integer. – The_Mundane Apr 23 '14 at 07:43
  • Check if strspn(str, "0123456789) == strlen(str) – cup Apr 23 '14 at 07:43
  • It's better to decide on either C _xor_ C++. What if someone posts the perfect C answer, and another one posts the perfect C++ answer? Which one will you accept? -- edit: I will remove the C++ tag for you have C answers by now. -- edit: Because the chaos succeeded, I will add the C++ tag again. – Sebastian Mach Apr 23 '14 at 07:44
  • You could try , if that suits you. – user1095108 Apr 23 '14 at 07:46

4 Answers4

3

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).

Basile Starynkevitch
  • 216,767
  • 17
  • 275
  • 509
  • Why `if (end && ...)`? Do you mean `if (end > cstr && ...)`? And you have also check for "overflow", compare this answer http://stackoverflow.com/a/1640804/1187415 to the duplicate question. – Martin R Apr 23 '14 at 07:47
3

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

user657267
  • 19,994
  • 5
  • 55
  • 75
  • 1
    It's worth noting that these also throw an exception if you try to convert a string containing 1323723172981729817298798271972198728917918729817928 - since it's bigger than the biggest integer. (And that there are `unsigned` variants of all of the above). – Mats Petersson Apr 23 '14 at 07:47
  • @MatsPetersson `float`ing variants too – user657267 Apr 23 '14 at 07:47
1

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

Andrey Chernukha
  • 21,004
  • 16
  • 95
  • 160
1
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;
  }
}
Blaz Bratanic
  • 2,129
  • 11
  • 17