C++ – Convert String to Integer Vector
Prerequisite:
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.
Example:
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.
Example:
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string s = "12345" ;
vector< int > v(1, 0);
int j = 0;
for ( int i = 0; i < s.size(); i++) {
v[j] = v[j] * 10 + (s[i] - 48);
}
for ( auto val : v) {
cout << val << endl;
}
return 0;
}
|
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.
Example:
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string s = "12345" ;
vector< int > v;
v.push_back(stoi(s));
for ( auto val : v) {
cout << val << endl;
}
return 0;
}
|
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++.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string line = "1 2 3 4 5" ;
stringstream lineStream(line);
vector< int > numbers(istream_iterator< int >(lineStream),
{});
for ( auto it : numbers) {
cout << it << " " ;
}
cout << endl;
return 0;
}
|
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.
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str = "12345" ;
const char * s = str.c_str();
vector< int > v;
v.push_back( atoi (s));
for ( auto val : v) {
cout << val << endl;
}
return 0;
}
|
Last Updated :
07 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...