I want to convert the string str = "12 13 15 20"
into array of integers like int str_int[4]{12,13,15,20}
using c++.
Asked
Active
Viewed 3,124 times
-6

Edward A
- 2,291
- 2
- 18
- 31

Mohammad Karam
- 1
- 1
- 2
-
What do you have already? – PMF May 16 '14 at 13:49
-
Create a `stringstream` from it and `while (stream >> val)` push it back on a `vector`. `-1` for lack of effort. – Bartek Banachewicz May 16 '14 at 13:52
-
-1 (and close vote) for lack of effort. Consider doing a search on stack overflow. – utnapistim May 16 '14 at 14:00
-
@utnapistim Doesn't matter, he still got answers. – sashoalm May 16 '14 at 14:00
1 Answers
2
You can use stringstream:
#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main()
{
std::string s = "12 13 15 20";
std::stringstream ss( s);
int i;
std::vector<int> v;
while( ss >> i)
v.push_back( i);
std::copy( v.begin(), v.end(),
std::ostream_iterator<int>( std::cout, ","));
return 0;
}
Another option is:
std::copy( std::istream_iterator<int>( ss), std::istream_iterator<int>(),
std::back_inserter(v));

4pie0
- 29,204
- 9
- 82
- 118
-
`std::copy(std::istream_iterator
(is), std::istream_iterator – Massa May 16 '14 at 14:25(), std::back_inserter(v));` would also work instead of the `while`... -
-