How to convert a string to an integer in C
C gives you three main functions to turn text into a whole number: atoi(), strtol(), and sscanf(). The choice depends on how much error-checking you need and what happens if the text isn't actually a number.
atoi() is the simplest. You pass it a string, and it returns an integer. If the string is "42", you get the number 42. If the string is "hello", you get 0 — and that's the catch. atoi() gives you no way to tell whether the conversion worked or failed, so it's only safe when you're certain the input is valid.
strtol() is more powerful. It converts the string and also tells you whether it succeeded. It can handle different number bases (binary, octal, decimal, hexadecimal) and sets an error indicator if something goes wrong. Most production code uses strtol() because you can actually detect bad input.
sscanf() works like reading formatted input from a string instead of from the keyboard. It's useful when you're parsing a string that contains multiple pieces of data, but it's slower than strtol() for a single conversion.
Key Takeaways
- Use atoi() only when you know the string contains a valid number, because it returns 0 for both "0" and invalid input with no way to tell the difference.
- strtol() is the safest choice for real programs because it reports whether the conversion succeeded and lets you detect bad input.
- All three functions skip leading whitespace automatically, so " 42" converts the same way as "42".
- If your string contains text after the number, like "42 apples", strtol() will convert the 42 and stop, while atoi() will also convert just the 42.
- For negative numbers, all three functions handle the minus sign correctly as long as it comes right after any whitespace.
Using atoi() for simple cases
The atoi() function lives in the stdlib.h header. You include it, pass a string, and get back an int:
#include <stdlib.h> goes at the top of your file. Then you write int num = atoi("42"); and num holds 42. The function scans from the start of the string, skips any spaces, reads digits (and a leading + or - sign), and stops as soon as it hits a non-digit character.
The problem is that atoi() returns 0 if the string is "0", and also returns 0 if the string is "abc" or NULL or empty. Your code cannot tell the difference. For a homework assignment or a small script where you control the input, this is fine. For anything that reads user input or data from a file, you need strtol().
Using strtol() for reliable conversion
The strtol() function also lives in stdlib.h and gives you error detection. The signature is long strtol(const char *str, char **endptr, int base);. You pass the string, a pointer to a char pointer (which strtol() will set to point at the first character it didn't convert), and the base (10 for decimal, 16 for hex, 2 for binary, 0 to auto-detect).
Here's the pattern: declare a char pointer, call strtol(), and check whether endptr points back at the start of the string. If it does, nothing was converted. If it points partway through, some characters were converted and some were not. If it points at a null terminator or whitespace, the whole number was converted:
char *endptr;long num = strtol("42", &endptr, 10);if (endptr == str) { /* conversion failed */ }
strtol() also sets errno to ERANGE if the number is too large or too small to fit in a long. Check errno after calling strtol() if you're working with very large numbers. Remember that strtol() returns a long, not an int, so cast it down if you need an int: int num = (int)strtol("42", &endptr, 10);
Handling different number bases with strtol()
If you pass 16 as the base, strtol() reads hexadecimal: "FF" becomes 255. Pass 2 and it reads binary: "1010" becomes 10. Pass 8 and it reads octal: "77" becomes 63. Pass 0 and strtol() auto-detects: strings starting with "0x" are hex, strings starting with "0" are octal, everything else is decimal.
This is useful when parsing configuration files or command-line arguments that might contain hex color codes or permission bits. For everyday decimal conversion, pass 10 as the base.
Using sscanf() for formatted strings
The sscanf() function reads formatted data from a string the way scanf() reads from keyboard input. You pass the string, a format string, and a pointer to where you want the result:
#include <stdio.h>int num;sscanf("42", "%d", &num);
sscanf() returns the number of items successfully converted. If you ask it to convert "42" with format "%d", it returns 1. If you ask it to convert "abc" with format "%d", it returns 0. This makes error detection straightforward: check the return value.
sscanf() shines when your string contains multiple pieces: sscanf("42 3.14 hello", "%d %lf %s", &intval, &floatval, stringval); converts all three at once. For a single integer, strtol() is faster, but sscanf() is clearer if you're already parsing a structured format.
Common mistakes and how to avoid them
The most common mistake is forgetting to pass a pointer to endptr in strtol(). You must pass the address of a char pointer, not a char pointer itself. Write &endptr, not endptr.
Another mistake is assuming atoi() will tell you if the conversion failed. It won't. If you need to know whether the input was valid, use strtol() or sscanf().
A third mistake is forgetting that strtol() returns a long, not an int. If you assign it directly to an int variable, the compiler may warn you. Cast it explicitly: int num = (int)strtol(str, &endptr, 10);
Finally, remember that all three functions stop at the first non-digit character. "42 apples" converts to 42, not an error. If you need to reject strings with trailing text, check what endptr points to after conversion.
Frequently Asked Questions
What's the difference between atoi() and strtol()?
atoi() is simpler but gives no error information — it returns 0 for both "0" and "invalid". strtol() tells you exactly where the conversion stopped and whether it succeeded, making it safer for real programs.
Can I convert a string to a negative number?
Yes. All three functions handle a leading minus sign: "-42" converts to negative 42. The minus sign must come right after any leading whitespace and before the digits.
What happens if the number is too big to fit in an int?
With atoi(), the result is undefined — the behavior depends on your compiler. With strtol(), the function returns LONG_MAX or LONG_MIN and sets errno to ERANGE, so you can detect the overflow.
Can I convert hexadecimal strings like "0xFF"?
Yes, with strtol(). Pass 16 as the base: strtol("0xFF", &endptr, 16) returns 255. You can also pass 0 as the base and strtol() will auto-detect the base from the prefix (0x for hex, 0 for octal, nothing for decimal).
Which function should I use in my code?
Use strtol() by default. It's reliable, detects errors, and handles edge cases. Use atoi() only if you're certain the input is valid. Use sscanf() if you're parsing a string with multiple formatted values.