Convert String to Integer or Float or Double
Sometimes, we need to convert string data type (numeric character) into integer or float or double type for mathematical calculation.
In C programming, string (numeric character) can be converted into an integer or a float or a double type using the sscanf() function.
The sscanf() takes 3 arguments: (1) string data to be formatted, (2) format specifier, and (3) output variable for converted data .
Convert String into Integer in C
In C programming, use "%d" format specifier to convert a string into an integer using the sscanf() function as demonstrated in the following example:
Examples of Converting String into Integer
Example explained
-
int outputInteger;: The line declares an integer variable named 'outputInteger'. -
const char* stringVariable = "125";: The line declares a pointer variable named 'stringVariable' and assigns numeric characters "125". -
sscanf(stringVariable, "%d", &outputInteger);: The sscanf() function converts the string data into an integer and pass the integer data to the 'outputInteger' variable. -
int newSum = outputInteger + 25;: This adds 25 to the 'outputInteger' variable and assigns the sum to the 'newSum' variable. -
printf("%d\n", newSum);: It prints the sum of the integer numbers.
Convert String into Float in C
In C programming, use "%f" format specifier to convert a string into a float using the sscanf() function as demonstrated in the following example:
Examples of Converting String into Float
Example explained
-
float outputFloat;: The line declares a float variable named 'outputFloat'. -
const char* stringVar = "125.25";: The line declares a pointer variable named 'stringVariable' and assigns numeric characters "125.25". -
sscanf(stringVar, "%f", &outputFloat);: The sscanf() function converts the string data into a float and pass the float data to the 'outputFloat' variable. -
float newFSum = outputFloat + 25.50;: This adds 25.20 to the 'outputFloat' variable and assigns the sum to the 'newFSum' variable. -
printf("%f\n", newFSum);: It prints the sum of the float numbers.
Convert String into Double in C
In C programming, use "%lf" format specifier to convert a string into a double using the sscanf() function as demonstrated in the following example:
Examples of Converting String into Double
Example explained
-
double outputDouble;: The line declares a double variable named 'outputDouble'. -
const char* stringNumVar = "125.255";: The line declares a pointer variable named 'stringNumVar' and assigns numeric characters "125.255". -
sscanf(stringNumVar, "%lf", &outputDouble);: The sscanf() function converts the string data into a double and pass the double data to the 'outputDouble' variable. -
double newDSum = outputDouble + 25.205;: This adds 25.205 to the 'outputDouble' variable and assigns the sum to the 'newDSum' variable. -
printf("%lf\n", newDSum);: It prints the sum of the double numbers.