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.
Asked
Active
Viewed 141 times
1

Deanie
- 2,316
- 2
- 19
- 35

The_Mundane
- 107
- 1
- 1
- 10
-
1It 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 Answers
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
- 223,805
- 18
- 296
- 547
-
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
- 20,568
- 5
- 58
- 77
-
1It'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
-
1
You could also loop through the string and appply isdigit
function to each character

Andrey Chernukha
- 21,488
- 17
- 97
- 161
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,279
- 12
- 17