使用stringstream分割字符串

#include <iostream>
#include <sstream>
 
using namespace std;
 
int main() {
    stringstream ss("i,love, you");
    string token;
    while (getline(ss, token)) { /* mark */
        cout << token << endl;
    }
    return 0;
}

getline可以传入额外的分割符参数,类型为const char*,默认是换行符\n. 上面的代码片段mark处可变:

while (getline(ss, token)) 输出

i,love, you

while (getline(ss, token, ' ')) 输出

i,love,
you

while (getline(ss, token, ',')) 输出

i
love
 you

读取两行整数,每一行放入一个vector

#include <iostream>
#include <vector>
#include <sstream>
 
using namespace std;
 
int main()
{
  vector<int> v1, v2;
  for (int i = 0; i != 2; ++i)
  {
    string line;
    std::getline(cin, line);
    istringstream is(line);
    if (i == 0)
    { // use implicit conversion
      for (int val; is >> val; v1.push_back(val)) { }
    }
    else
    { // or use std::stoi
      for (string val; is >> val; v2.push_back(std::stoi(val))) { }
    }
  }
 
  for (auto e : v1) cout << e << " ";
  cout << endl;
  for (auto e : v2) cout << e << " ";
 
  return 0;
}