参考:(2条消息) C++分割带逗号的字符串_九霄星河的博客-CSDN博客_c++ 逗号分隔字符串
原理:
第一步:接收字符串 s ;
第二步:遍历字符串 s ,把 s 中的逗号换成空格;
第三步:通过 istringstream 类重新读取字符串 s ;
注意, istringstream 这个类包含在库 < sstream > 中,所以头文件必须包含这个库。
#include<bits/stdc++.h>
#include<sstream>
#include<string>
using namespace std;
int main() {
vector<int> nums;
string s = "0,12,123,1234";
int n = s.size();
for(int i = 0; i < n; i++) {
if(s[i] == ',') s[i] = ' ';
}
istringstream out(s);
string str;
while(out >> str) {
nums.push_back(stoi(str));
}
for(int num:nums) {
cout<<num<<endl;
}
return 0;
}
结果: