Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a string by whitespace into a vector

Tags:

c++

string

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

like image 554
Steffan Harris Avatar asked Apr 29 '12 03:04

Steffan Harris


1 Answers

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) {
    v.push_back(tmp);
  }

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

}
like image 160
Israel Unterman Avatar answered Oct 10 '22 20:10

Israel Unterman