atoi in C: solved exercise
atoi in C: solved exercise
If you searched for a solved atoi exercise in C, here are the key patterns: converting strings to integers with atoi, understanding its limitations (no error handling), and the recommended alternative with strtol that can detect invalid input.
atoi (ASCII to integer) is the simplest conversion function, but it returns 0 for both "0" and invalid input like "abc", making it unsuitable when you need to distinguish an error from a legitimate zero value.
Problem statement
- Convert the strings
"42","-17"," 100 ", and"3abc"withatoiand print the results. - Repeat the conversions with
strtol, detecting format errors and overflow.
C solution
Expected output
Common mistakes
- Using
atoito validate user input: it returns 0 for both"abc"and"0", with no way to distinguish between the two. - Not setting
errno = 0beforestrtol:errnomay contain a value from a previous operation, causing false positive errors. - Not checking that
end != s: ifend == s, no digits were consumed — the string did not contain a number. - Confusing
strtol’s third parameter (the base) with a length:strtol(s, &end, 10)uses base 10; passing0auto-detects0x(hex) and leading0(octal).
Practical use
String-to-integer conversion appears in command-line argument parsing, configuration file reading, and network data deserialization. strtol is the industry standard for this purpose in C.
Recommended next exercise
- strtol in C: solved exercise
- strtok in C: solved exercise
- sprintf and snprintf in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
When is it fine to use atoi and when is strtol necessary?
atoi is acceptable in quick code where you know for certain the input is a valid integer (for example, after validating with isdigit). Use strtol when input comes from the user, a file, or the network and you need to distinguish errors from legitimate values.
How does strtol convert in other bases?
The third parameter is the base: strtol(s, &end, 16) converts hexadecimal, strtol(s, &end, 2) binary. With 0 it auto-detects the prefix: 0x for hex, a leading 0 for octal, and no prefix for decimal.
Is there an equivalent for double?
Yes: strtod(s, &end) converts a string to double using the same error-detection mechanism via the end pointer.