Convert a String to an Integer in C
In C programming, turning a sequence of characters that represents a number into an actual integer value is a common task, especially when processing user input, reading configuration files, or parsing data from networks. Now, although the language does not provide a built‑in conversion operator like some higher‑level languages, the C standard library offers several functions that perform this conversion safely and efficiently. Understanding how these functions work, what pitfalls to avoid, and how to implement your own solid converter when needed is essential for writing reliable code.
Why Convert Strings to Integers?
Applications often receive numeric data as text. Examples include:
- Command‑line arguments (
argv) that are always strings. - Input read from
stdinor files viafgets. - Data extracted from protocols such as HTTP or CSV.
- Configuration values stored in INI, JSON, or XML files.
Converting these strings to integers enables arithmetic operations, array indexing, and logical comparisons that would otherwise be impossible or error‑prone if the data remained as character arrays.
Standard Library Functions for Conversion
The C standard library (<stdlib.h> and <stdio.Consider this: h>) provides a family of functions designed to turn strings into numeric types. Each has its own strengths and weaknesses.
| Function | Returns | Base | Error Detection |
|---|---|---|---|
atoi |
int |
10 | None (returns 0 on failure) |
atol |
long |
10 | None |
atoll |
long long |
10 | None |
strtol |
long |
Any (2‑36) | Sets errno, returns LONG_MIN/LONG_MAX on overflow |
strtoul |
unsigned long |
Any (2‑36) | Sets errno, returns 0/ULONG_MAX on overflow |
strtoll |
long long |
Any (2‑36) | Sets errno, returns LLONG_MIN/LLONG_MAX on overflow |
strtoull |
unsigned long long |
Any (2‑36) | Sets errno, returns 0/ULLONG_MAX on overflow |
sscanf |
varies | Any (via format) | Returns number of successful assignments; can detect mismatches |
Among these, strtol (and its unsigned/long‑long counterparts) is generally preferred because it offers explicit base selection, detailed error reporting, and overflow detection.
Detailed Look at strtol
long strtol(const char *nptr, char **endptr, int base);
nptr– pointer to the string to convert.endptr– if notNULL, stores the address of the first character after the number; useful for detecting trailing garbage.base– numeric base for interpretation.0lets the function auto‑detect based on prefixes (0x/0Xfor hex,0for octal, otherwise decimal). Valid values are2‑36.
Step‑by‑Step Conversion Process
- Skip leading whitespace – characters for which
isspace()returns true are ignored. - Optional sign – a leading
+or-is recorded. - Prefix detection (if base == 0) –
0xor0X→ hexadecimal (base 16)0→ octal (base 8)- otherwise → decimal (base 10)
- Digit accumulation – each subsequent character is checked against the valid digit set for the chosen base. Valid digits are
0‑9,A‑Z,a‑z(values 10‑35). Conversion stops at the first invalid character. - Overflow detection – before multiplying the accumulator by the base and adding the next digit, the function checks whether the operation would exceed the limits of a
long. If overflow would occur,errnois set toERANGEand the function returnsLONG_MAX(for positive overflow) orLONG_MIN(for negative overflow). - Store end pointer – if
endptris non‑NULL, it is set to point to the character that stopped the conversion (either the first invalid character or the terminating'\0'). - Return value – the converted signed long integer.
Example Usage
#include
#include
#include
#include
int main(void) {
const char *input = " -42apples";
char *end;
errno = 0; // reset errno before call
long val = strtol(input, &end, 10);
if (errno == ERANGE) {
perror("strtol overflow");
} else if (end == input) {
fprintf(stderr, "No digits were found\n");
} else {
printf("Converted value: %ld\n", val);
if (*end != '\0') {
printf("Remaining text: \"%s\"\n", end);
}
}
return 0;
}
This is the bit that actually matters in practice Small thing, real impact..
Output
Converted value: -42
Remaining text: "apples"
The program demonstrates proper error checking: errno detects overflow, endptr reveals whether any conversion happened, and the leftover string can be processed further (e.g., for unit parsing).
Handling Different Bases
When base is supplied explicitly (e.On top of that, , 16 for hexadecimal), the function ignores the usual 0x prefix unless the base is 0. g.This flexibility lets you parse strings like "FF" as 255 when you call strtol(str, NULL, 16) Less friction, more output..
strtol("0x1A", NULL, 0); // returns 26 (hex)
strtol("0755", NULL, 0); // returns 493 (octal)
strtol("123", NULL, 0); // returns 123 (decimal)
Alternative: Using sscanf
sscanf can also convert strings to integers, offering format‑string control similar to printf. Example:
int i;
if (sscanf("42", "%d", &i) == 1) {
printf("Parsed %d\n", i);
} else {
puts("Conversion failed");
}
Pros
- Familiar format syntax.