Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert a string to a integer in C
In C programming, converting a string to an integer is a common task that can be accomplished using several built-in functions. The most commonly used functions are atoi(), strtol(), and sscanf().
Syntax
int atoi(const char *str); long strtol(const char *str, char **endptr, int base); int sscanf(const char *str, const char *format, ...);
Method 1: Using atoi() Function
The atoi() function converts a string to an integer. It stops reading when it encounters a non-digit character −
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
int num = atoi(str);
printf("String: %s
", str);
printf("Integer: %d
", num);
return 0;
}
String: 12345 Integer: 12345
Method 2: Using strtol() Function
The strtol() function provides better error handling and allows you to specify the base for conversion −
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "1999";
char *endptr;
long num = strtol(str, &endptr, 10);
if (*endptr == '\0') {
printf("String: %s
", str);
printf("Integer: %ld
", num);
} else {
printf("Conversion failed
");
}
return 0;
}
String: 1999 Integer: 1999
Method 3: Extracting Numbers from Strings
Here's an example that extracts a year from a movie title string −
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *name = "The Matrix(1999)";
char *ps;
char year_str[5] = "";
int year, i;
/* Find the opening bracket */
ps = strchr(name, '(');
if (ps != NULL) {
/* Extract characters between brackets */
for (i = 1; i < strlen(ps) - 1 && i < 5; i++) {
year_str[i-1] = ps[i];
}
year_str[4] = '\0';
/* Convert to integer */
year = atoi(year_str);
printf("Movie: %s
", name);
printf("Year: %d
", year);
}
return 0;
}
Movie: The Matrix(1999) Year: 1999
Key Points
-
atoi()is simple but has no error checking -
strtol()provides better error handling and base conversion - Always ensure the string contains valid numeric characters
- Use
strchr()to locate specific characters in strings
Conclusion
Converting strings to integers in C can be done using atoi() for simple cases or strtol() for better error handling. Choose the method based on your specific requirements for error checking and validation.
Advertisements
