Converting strings to integers with atoi and atol
What you'll learn: How to transform strings containing digits into actual numeric variables that your program can use for calculations.
The translation problem
In C, there is a big difference between the character '5' and the integer 5. Computers see the character as a symbol for display, while they see the integer as a value for math. When you receive input from a user or a file, it almost always arrives as a string (a sequence of characters). To add, subtract, or compare these inputs as numbers, you need a translator.
The <stdlib.h> library provides two simple functions for this: atoi (ASCII to integer) and atol (ASCII to long integer).
How they work
Think of these functions like a specialized translator at a customs desk. They look at a string, ignore any leading whitespace, and start reading digits. As soon as they hit a character that isn't a number (like a letter or a space), they stop and hand you the result they've gathered so far.
atoi("42")returns the integer42.atol("2147483648")returns alonginteger, which is necessary for numbers too large for a standardint.
A simple example
Here is how you might convert a string "123" into an actual number you can perform math on:
#include <stdio.h>
#include <stdlib.h> // Required for atoi and atol
int main() {
char ageString[] = "25";
char populationString[] = "8000000";
// Convert string to a standard integer
int age = atoi(ageString);
// Convert string to a long integer
long population = atol(populationString);
// Now we can do math!
int nextYear = age + 1;
printf("Next year you will be %d.\n", nextYear);
printf("The city population is %ld.\n", population);
return 0;
}
A word of caution
These functions are simple, but they aren't very smart. If you try to convert a string that doesn't start with a number (like atoi("hello")), the function will simply return 0. Because 0 is also a valid number, atoi cannot tell you if the conversion failed or if the user actually typed "0". For basic tools and quick conversions, however, they are the go-to functions in the C Standard Library.
Key takeaway
Use atoi for standard integers and atol for large integers to convert numeric strings into values you can use for math.