26

I have a string which contains some number of integers which are delimited with spaces. For example

string myString = "10 15 20 23";

I want to convert it to a vector of integers. So in the example the vector should be equal

vector<int> myNumbers = {10, 15, 20, 23};

How can I do it? Sorry for stupid question.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
mskoryk
  • 506
  • 1
  • 5
  • 12

3 Answers3

37

You can use std::stringstream. You will need to #include <sstream> apart from other includes.

#include <sstream>
#include <vector>
#include <string>

std::string myString = "10 15 20 23";
std::stringstream iss( myString );

int number;
std::vector<int> myNumbers;
while ( iss >> number )
  myNumbers.push_back( number );
Abhishek Bansal
  • 12,589
  • 4
  • 31
  • 46
  • 1
    I think adding also the include statements will make this answer even better. – Wolf Dec 18 '13 at 13:30
  • I mean all (+vector) - and also the [using declarations](http://en.cppreference.com/w/cpp/language/using_declaration) necessary to make it compile. I'll keep my (+1) ready :) – Wolf Dec 18 '13 at 13:45
  • ...BTW: **I love this** `while (iss >> number)` :-) – Wolf Dec 18 '13 at 13:50
  • Great! (+1d) Another alternative was `using std::vector; using std::stringstream; using std::string;` – Wolf Dec 18 '13 at 13:55
12
std::string myString = "10 15 20 23";
std::istringstream is( myString );
std::vector<int> myNumbers( ( std::istream_iterator<int>( is ) ), ( std::istream_iterator<int>() ) );

Or instead of the last line if the vector was already defined then

myNumbers.assign( std::istream_iterator<int>( is ), std::istream_iterator<int>() );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 3
    It would be more correctly to write the last line as std::vector myNumbers( ( std::istream_iterator( is ) ), std::istream_iterator() ); that is to enclose the first argument in parentheses. Otherwise instead of the vector definition it will be a function declaration.:) – Vlad from Moscow Dec 18 '13 at 13:23
  • 2
    Or you could use initializer list construct that is designed to solve that problem. `std::vector myNumbers{ std::istream_iterator( is ), std::istream_iterator() };` – Martin York Dec 18 '13 at 13:59
0

This is pretty much a duplicate of the other answer now.

#include <iostream>
#include <vector>
#include <iterator>
#include <sstream>

int main(int argc, char* argv[]) {
    std::string s = "1 2 3 4 5";
    std::istringstream iss(s);
    std::vector<int> v{std::istream_iterator<int>(iss),
                       std::istream_iterator<int>()};
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
}
  • No need to use `std::copy`. Because `std::vector` has a constructor that takes two iterators (just like std::copy). – Martin York Dec 18 '13 at 14:01
  • 2
    Also the the *good old for loop* for output should better be not included here, because it's *not easy*. – Wolf Dec 18 '13 at 14:49