在使用 cin 读取 string 时,默认以空格、制表符、换行符为分隔,如:
Hello world!
hello cpp
\0
如果每行的输入以逗号为分隔符该怎么读取:
Hello,world!
hello,cpp
\0
先读取一行,然后使用 <sstream>
中的 stringstream
从一行字符串中按逗号分隔读取各个子串:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string str1;
while(cin >> str1){
// 遇到 \0 跳出循环
if (str1 == "\\0")
break;
stringstream ss(str1);
string tmp;
while(getline(ss, tmp, ',')){
cout << tmp << " ";
}
cout << endl;
}
return 0;
}