String to int Conversion Using stringstream Class
The stringstream class in C++ allows us to associate a string to be read as if it were a stream. We can use it to easily convert strings of digits into ints, floats, or doubles. The stringstream class is defined inside the <sstream> header file.
It works similar to other input and output streams in C++. We first create a stringstream object as shown below:
Syntax:
stringstream ss;
Then insert a numeric string into it using the ( << ) insertion operator.
Example:
ss << myString; ss << myCstring; ss << myInt; or float, or double, etc.
At last, we extract the numeric value from the stream using the ( >> ) extraction operator.
Example:
ss >> myChar; ss >> myCstring; ss >> myInt;
The below C++ program demonstrates how to convert a string to int using a stringstream object:
C++
// C++ program to demonstrate the // use of a stringstream to // convert string to int #include <iostream> #include <sstream> using namespace std; // Driver code int main() { string s = "12345" ; // object from the class stringstream stringstream geek; // inserting string s in geek stream geek << s; // The object has the value 12345 // and stream it to the integer x int x = 0; geek >> x; // Now the variable x holds the // value 12345 cout << "Value of x + 1 : " << x + 1; return 0; } |
Value of x + 1 : 12346
To summarize, stringstream is a convenient way to manipulate strings. This method also works for both C style strings or C++ style strings.
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