C++ – Convert String to Integer Vector
Conversion of string to integer is one of the common tasks done in C++, but it gets quite complex when there are multiple integer values present. So to solve this problem we can store values inside a vector.
string str=”123″ ;
// conversion to store it inside vector<int>
// Storing this value inside vector [ 123 ]
Converting string to Integer Vector can be done using 3 methods:
- Using ASCII values
- Using Stoi()
- Using stringstream
1. Using ASCII values for conversion
The above code converts each character of the string “12345” into elements of a vector of int type. Also, there is another way by which we could try to convert a string into an integer vector.
2. Using Stoi( )
There is another method that we could use to convert string to int and hence from string to vector of int as well. We could use the “stoi()” function. This method is used with the newer version of C++. Basically, with C++11 and more. It takes a string value as input and returns an integer value as output.
3. Using string stream for conversion
stringstream is a feature where a string can be treated as a stream, stream allowing you to read from the string. stringstream can be used using sstream header file.
To know more about this, refer to the article – stringstream in C++.
1 2 3 4 5
4. Using atoi( )
We could also convert strings to integers with the help of atoi() function. In this approach, first convert the string to a character array and then this character array is converted to a vector of integers using atoi() function. atoi() takes a character array as input and returns an integer value as output.
Please Login to comment...