Converting String to int Using sscanf()
‘sscanf()‘ is a C-style function similar to scanf(). It reads input from a string rather than standard input.
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.
Return:
- On success, the function returns the number of variables filled.
- In the case of an input failure, before any data could be successfully read, the end of the function(EOF) is returned.
Example:
C++
// C++ program to demonstrate // the working of sscanf() to // convert a string into a number #include <iostream> using namespace std; int main() { const char * str = "12345.0000046" ; float x; sscanf (str, "%f" , &x); cout << "The value of x : " << x << endl; return 0; } |
The value of x : 12345
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. 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. Conversion is mostly done so that we can convert numbers that are stored as strings.
Example:
str=”191″
num=191
There are 5 significant methods to convert strings to numbers in C++ as follows:
- Using stoi() function
- Using atoi() function
- Using stringstream
- Using sscanf() function
- Using for Loop
- Using strtol() function