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
Converting Strings to Numbers in C/C++
In C programming, converting strings to numbers is a common task that can be accomplished using several standard library functions. C provides multiple approaches to convert string representations of numbers into their corresponding numeric values.
Syntax
int atoi(const char *str); long atol(const char *str); double atof(const char *str); long strtol(const char *str, char **endptr, int base); double strtod(const char *str, char **endptr);
Method 1: Using atoi() for Integer Conversion
The atoi() function converts a string to an integer value −
#include <stdio.h>
#include <stdlib.h>
int main() {
char str1[] = "45";
char str2[] = "3.14159";
char str3[] = "31337 geek";
int num1 = atoi(str1);
int num2 = atoi(str2);
int num3 = atoi(str3);
printf("atoi("%s") is %d\n", str1, num1);
printf("atoi("%s") is %d\n", str2, num2);
printf("atoi("%s") is %d\n", str3, num3);
return 0;
}
atoi("45") is 45
atoi("3.14159") is 3
atoi("31337 geek") is 31337
Method 2: Using atof() for Float Conversion
The atof() function converts a string to a floating-point number −
#include <stdio.h>
#include <stdlib.h>
int main() {
char str1[] = "45.67";
char str2[] = "3.14159";
char str3[] = "123.45abc";
double num1 = atof(str1);
double num2 = atof(str2);
double num3 = atof(str3);
printf("atof("%s") is %.2f\n", str1, num1);
printf("atof("%s") is %.5f\n", str2, num2);
printf("atof("%s") is %.2f\n", str3, num3);
return 0;
}
atof("45.67") is 45.67
atof("3.14159") is 3.14159
atof("123.45abc") is 123.45
Method 3: Using strtol() for Advanced Integer Conversion
The strtol() function provides more control and error checking −
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "123abc456";
char *endptr;
long num = strtol(str, &endptr, 10);
printf("Converted number: %ld\n", num);
printf("Remaining string: "%s"\n", endptr);
/* Converting hexadecimal */
char hex[] = "FF";
long hexNum = strtol(hex, NULL, 16);
printf("Hex %s to decimal: %ld\n", hex, hexNum);
return 0;
}
Converted number: 123 Remaining string: "abc456" Hex FF to decimal: 255
Key Points
- atoi() and atof() stop at the first non-numeric character and return the converted portion.
- strtol() and strtod() provide better error handling and can detect conversion failures.
- These functions ignore leading whitespace but stop at the first invalid character.
- For invalid input,
atoi()returns 0, whilestrtol()allows checking for errors.
Conclusion
C provides multiple functions for string-to-number conversion. Use atoi() and atof() for simple conversions, and strtol() or strtod() when you need error handling and more control over the conversion process.
Advertisements
