String conversion
- C course
- Intermediate
- Lesson 21/116
- 5 min
Learn conversion with atoi, atof and strtol.
Converting to integer with atoi
atoi(s) converts a string to an int. The name means "ASCII to integer". It's declared in <stdlib.h>.
Example: int n = atoi("42");. Here n becomes 42. atoi skips leading whitespace and parses the number; on invalid input the behavior is undefined, usually 0. For safe conversion strtol is preferred; it reports errors via a separate parameter. atof works similarly for double.
Safe conversion with strtol
strtol(s, &end, 10) converts a string to a long integer; the second parameter says where parsing stopped, the third the base (10 for decimal).
Example: char *end; long v = strtol("42abc", &end, 10);. Here v becomes 42; end points to the "abc" part. This gives you both the value and the leftover. Unlike atoi, strtol explicitly reports errors; that's why it's preferred in production. atof works similarly for double.
Practice Convert a string to int and double
Convert to integer with int n = atoi("42");. Convert to double with double d = atof("3.14");. Print both with printf("%d\n", n); and printf("%f\n", d);. Include <stdlib.h>.
Starter code
#include <stdio.h>
#include <stdlib.h>
// Convert "42" to int with atoi
// Convert "3.14" to double with atof
// Print both
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = atoi("42");
double d = atof("3.14");
printf("%d\n", n);
printf("%f\n", d);
return 0;
}Expected output
42 3.140000
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which function converts "42" to an int?
- strcat
- strlen
- atoi Correct answer
- strstr
Explanation: atoi converts a string to int; the name means ASCII to integer.
2 Match the conversion functions
| Term | Meaning |
|---|---|
atoi |
Converts to int |
atof |
Converts to double |
strtol |
Long and leftover |
sprintf |
Formatted write |
3 Complete the atof call
double pi = ____("3.14");
double pi = atof("3.14");
Explanation: atof converts a string to double.