C++ – Parse a string by whitespace into a vector


Suppose I have a string of numbers

"1 2 3 4 5 6"

I want to split this string and place every number into a different slot in my vector. What is the best way to go about this

Best Solution

Use istringstream to refer the string as a stream and >> operator to take the numbers. It will work also if the string contains newlines and tabs. Here is an example:

#include <vector>
#include <sstream>  // for istringstream
#include <iostream>  // for cout

using namespace std;  // I like using vector instead of std::vector

int main() 
  char *s = "1 2 3 4 5";
  istringstream s2(s);
  vector<int> v;
  int tmp;

  while (s2 >> tmp) {

  // print the vector
  for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
    cout << *it << endl;