How to use sscanf() In C Language
We can use sscanf() to easily convert a string to an integer. This function reads the formatted input from the string.
Syntax of sscanf:
int sscanf (const char * source, const char * formatted_string, ...);
Parameters:
- source – source string.
- formatted_string – a string that contains the format specifiers.
- … : – variable arguments list that contains the address of the variables in which we want to store input data.
There should be at least as many of these arguments as the number of values stored by the format specifiers. On success, the function returns the number of variables filled. In the case of an input failure, before any data could be successfully read, EOF is returned.
Example:
C
// C program to demonstrate // the working of SSCANF() to // convert a string into a number #include <stdio.h> int main() { const char * str1 = "12345" ; const char * str2 = "12345.54" ; int x; // taking integer value using %d format specifier for // int sscanf (str1, "%d" , &x); printf ( "The value of x : %d\n" , x); float y; // taking float value using %f format specifier for // float sscanf (str2, "%f" , &y); printf ( "The value of x : %f\n" , y); return 0; } |
The value of x : 12345 The value of x : 12345.540039
Can we typecast String to int?
The answer is NO. If we use typecasting to convert the string to a number, we will get an error as shown in the example below.
Example:
C
// C Program to check the output // of typecasting from string to integer #include <stdio.h> int main() { string str = "8" ; int num; // Typecasting num = ( int )str; return 0; } |
Output:
main.c: In function ‘main’: main.c:9:11: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] 9 | num = (int)str; | ^ 1683652612
Explanation: As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion.
In the above code, we can see the output gives the warning with any garbage value inside it. So, to avoid such conditions, we use the methods specified above.
Convert String to int in C
Converting string to int is a reoccurring task in the programming world. Despite being a simple task, many coders either fail or get confused while doing this. Conversion is mostly done so that we can perform operations over numbers that are stored as strings.
Example:
str=”163″
number=163
C is a strongly typed language. We’ll get an error if we try to input a value that isn’t acceptable with the data type. Not just in inputs but we will get an error while performing operations.
There are 3 methods to convert a string to int which are as follows:
- Using atoi( )
- Using Loops
- Using sscanf()
Contact Us