#include<iostream>
#include <sstream>
using namespace std;
int main(){
string a, b, c, d;
string lines="adfa;asdfasd;fasdf;ccc";
stringstream line(lines); //可以直接初始化
getline(line, a, 'f');
getline(line, b, ';'); //接收分割之后的前半部分
getline(line, c, ';');
getline(line, d); //与不同的getline搭配
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
cout<<"d = "<<d<<endl;
}
//运行结果
a = ad
b = a
c = asdfasd
d = fasdf;ccc
例题
class Solution {
public:
string sortSentence(string s) {
stringstream line(s);
vector<string> res(210);
string a;
while(getline(line,a,' ')){
int num = a[a.size() - 1] - '0';
res[num] = a.substr(0,a.size() - 1);
}
string ans;
for(int i = 0;i < 210;++i){
if(res[i] != "") ans += res[i] + ' ';
}
ans.erase(ans.end() - 1);
return ans;
}
};