What converting a string to an integer means, and why you need it
When you have text that looks like a number — "42" or "1000" — your C program sees it as a series of characters, not as a number you can do math with. Converting a string to an integer means telling C to read those characters and turn them into an actual number your code can add, subtract, or compare.
This matters when you're reading data from a file, getting input from a user, or processing text that contains numbers. If you try to add the string "5" to the string "3" in C, you won't get 8 — you'll get an error or unexpected behavior. You need the conversion step first.
Key Takeaways
- The atoi() function is the simplest way to convert a string to an integer, and it comes built into C's standard library.
- strtol() is more powerful and safer because it tells you if the conversion failed or if there were leftover characters.
- If your string contains non-numeric characters, atoi() will silently return 0, while strtol() will stop at the first non-digit and let you know where it stopped.
- Always include the correct header file — <stdlib.h> for atoi() and strtol(), and <string.h> if you're checking the string first.
Using atoi() for straightforward conversions
The atoi() function (short for "ASCII to integer") is the quickest way to convert. You pass it a string, and it returns an integer. Here's the basic form:
int result = atoi("42"); will set result to the number 42. If you're reading from a file or a variable, you'd write int result = atoi(my_string); where my_string is a character array or pointer containing text.
The catch: if the string doesn't start with digits, or if it's empty, atoi() returns 0 without telling you anything went wrong. If your string is "hello", atoi() gives you 0. If your string is "42abc", atoi() gives you 42 and ignores the "abc". This silent behavior can hide bugs, so use atoi() only when you're certain the input is valid.
Using strtol() when you need to know if something went wrong
strtol() (string to long) is more work to set up, but it tells you exactly what happened. You give it three things: the string, a pointer to store where the conversion stopped, and the number base (10 for decimal, 16 for hexadecimal, and so on).
Here's a real example:
char *string = "42 apples"; char *end_ptr; long result = strtol(string, &end_ptr, 10);
After this runs, result is 42, and end_ptr points to the space before "apples". You can check what end_ptr points to — if it's not the end of the string, you know there were leftover characters. If you pass an empty string or one that starts with letters, strtol() returns 0 and sets end_ptr to point to the start of the string, so you can detect the problem.
Use strtol() when your input comes from a file, user input, or anywhere you can't may provide it's clean. It takes a few more lines of code but prevents silent failures.
Handling errors and edge cases
If you're using strtol(), check the end pointer to see if the whole string was converted. A straightforward pattern is:
if (*end_ptr != '\0') { printf("Warning: leftover characters in string\n"); }
This checks whether end_ptr is pointing to the null terminator (the invisible character that marks the end of a string). If it's not, there were characters the function couldn't convert.
For very large numbers, strtol() can overflow — it returns LONG_MAX or LONG_MIN and sets errno to ERANGE. If you need to handle numbers larger than a long can hold, use strtoll() (string to long long) instead, which handles bigger integers.
Negative numbers and leading whitespace
Both atoi() and strtol() handle negative numbers automatically. If your string is "-42", both functions return -42 without any extra work. They also skip leading whitespace — if your string is " 42", both will read it as 42.
This is usually helpful, but it's worth knowing so you don't get surprised. If you need to reject strings with leading spaces, you can check the original string before conversion, or use strtol() and verify that end_ptr moved from the start of the string.
A complete example with error checking
Here's a realistic code snippet that converts a string from a file and handles problems:
#include <stdlib.h> #include <stdio.h> #include <errno.h> char buffer[50]; fgets(buffer, sizeof(buffer), stdin); char *end_ptr; long number = strtol(buffer, &end_ptr, 10); if (errno == ERANGE) { printf("Number too large\n"); } else if (*end_ptr != '\n' && *end_ptr != '\0') { printf("Invalid characters in input\n"); } else { printf("Converted to: %ld\n", number); }
This reads a line from input, converts it, and checks three things: whether it overflowed, whether there were leftover characters (accounting for the newline that fgets() includes), and whether the conversion succeeded. This pattern works for most real-world situations.
Frequently Asked Questions
What's the difference between atoi() and strtol()?
atoi() is simpler but silent when it fails — it returns 0 for invalid input with no way to tell if the input was actually "0" or garbage. strtol() tells you where the conversion stopped and whether it overflowed, so you can detect and handle errors. Use strtol() when input comes from outside your program.
Can I convert a string with decimal points like "3.14"?
Not with atoi() or strtol() — they stop at the decimal point. atoi("3.14") gives 3, and strtol() gives 3 with end_ptr pointing to the dot. To convert floating-point numbers, use atof() or strtod() instead.
What happens if the string is empty?
atoi("") returns 0. strtol("", &end_ptr, 10) also returns 0, but end_ptr points to the start of the string, so you can detect that nothing was converted. Check whether end_ptr moved to know if the string was actually empty or just contained "0".
Do I need to include any special headers?
Yes — include <stdlib.h> for atoi() and strtol(). If you're checking errno for overflow, also include <errno.h>. These are standard headers that come with every C compiler.
What if I need to convert to a different base, like hexadecimal?
strtol() handles this with the third parameter. strtol("FF", &end_ptr, 16) converts the hexadecimal string "FF" to 255. atoi() only works with base 10, so use strtol() if you need other bases.