1. Introduction: The Importance of String and Number Conversion in C
In C programming, converting between strings and numbers is a crucial operation. This is especially important when handling user input or processing data from external files, where you often need to convert strings to numbers. Conversely, it is also common to convert numbers to strings for displaying calculation results or writing logs.
There are several methods for such conversions, and choosing the right one depends on your use case. This article will explain in detail how to convert between strings and numbers in C, including error handling and safe practices.
2. How to Convert Strings to Numbers in C
Basic String-to-Integer Conversion Using atoi()
The most basic way to convert a string to an integer in C is to use the atoi()
function. This function is simple to use, but there are important caveats. Here’s a basic usage example:
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "123";
int num = atoi(str);
printf("Converted value: %dn", num);
return 0;
}
While atoi()
is simple, it lacks proper error checking. For example, it does not report an error even if the input is invalid. The following example shows how atoi()
behaves with an invalid string:
char str[] = "123abc";
int num = atoi(str); // Only "123" is converted; the rest is ignored
Because atoi()
returns the converted portion even if the string contains invalid characters, it should not be used in systems where safety and reliability are required.
Safe Conversion with strtol()
If error checking is needed, it is recommended to use the strtol()
function. strtol()
allows you to handle errors with invalid input, and also lets you specify the numerical base for conversion. Here’s an example of safely converting a string to an integer using strtol()
:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
char str[] = "123abc";
char *endptr;
errno = 0; // Reset error state
long num = strtol(str, &endptr, 10);
if (errno != 0 || *endptr != ' ') {
printf("Conversion failed.n");
} else {
printf("Converted value: %ldn", num);
}
return 0;
}
This code uses endptr
to detect invalid parts in the string, and also checks errno
to catch errors such as overflow or underflow.

3. How to Convert Numbers to Strings in C
The sprintf()
Function and Its Risks
To convert numbers to strings, use the sprintf()
function. sprintf()
converts a number to a string according to the specified format and writes it to a buffer. However, be careful about buffer overflow risks. Here’s a basic example:
#include <stdio.h>
int main() {
int num = 123;
char str[10];
sprintf(str, "%d", num);
printf("Converted string: %sn", str);
return 0;
}
While this converts an integer to a string, if the resulting string exceeds the buffer size, a buffer overflow may occur.
Safe Conversion with snprintf()
To prevent buffer overflow, it is recommended to use snprintf()
. snprintf()
lets you specify the buffer size, and output exceeding that size will be truncated. Here’s an example:
#include <stdio.h>
int main() {
int num = 12345;
char str[5];
snprintf(str, sizeof(str), "%d", num);
printf("Converted string: %sn", str); // Result is "1234" because buffer is too small
return 0;
}
In this example, the output is truncated because it exceeds the buffer size. snprintf()
is a safe way to avoid buffer overflows by explicitly setting the buffer length.
4. Practical Example: Bidirectional Conversion Between Strings and Numbers
In C, it is common to convert strings to numbers and vice versa. The following code demonstrates bidirectional conversion using sscanf()
and snprintf()
:
#include <stdio.h>
int main() {
char str[] = "12345";
int num;
sscanf(str, "%d", &num);
printf("String to number: %dn", num);
char new_str[10];
snprintf(new_str, sizeof(new_str), "%d", num);
printf("Number to string: %sn", new_str);
return 0;
}
Here, sscanf()
is used to convert a string to a number, and then snprintf()
converts the number back to a string. Bidirectional conversion is extremely useful when processing input data and displaying results.
5. Error Handling and Important Points
Handling Overflow and Underflow
When converting numbers to strings, overflow or underflow may occur. If the converted value exceeds the range of the data type, errors may result. When using strtol()
or sscanf()
, it is important to handle errors appropriately, as shown below:
if (errno == ERANGE) {
printf("Overflow or underflow occurred.n");
}
By checking errno
, you can determine if an error has occurred. Proper error handling for overflow and underflow prevents your program from behaving unexpectedly.
How to Handle Invalid Input
If the string format is invalid, conversion to a number will fail. For example, trying to convert a string like "123abc"
will only convert the number portion, ignoring the rest. To prevent this, use the pointer returned by strtol()
to check for conversion errors.
char *endptr;
long num = strtol(str, &endptr, 10);
if (*endptr != ' ') {
printf("Invalid input detected.n");
}
6. Summary
To ensure the stability of your programs, always perform error checks and use safe methods for converting numbers and strings. While atoi()
is easy to use, it does not handle errors, so it is generally recommended to use safer functions such as strtol()
, sscanf()
, and snprintf()
.
String and number conversion in C is a fundamental skill for programmers. Mastering this skill will help you write more robust programs. Proper error handling and memory management also contribute to writing secure, reliable software.
Further Learning
If you want to learn more about this topic, consult the official documentation or review code from open-source projects. There are also many books on error handling and memory management in C, which are highly recommended.