第一种方法:使用cin.get(ch),循环检查输入缓冲区中的每个字符是否为空格、换行符,并进行分支处理,代码如下所示:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> arr;
string temp;
char ch;
while(cin.get(ch)) {
if((ch != ' ') && ch != '\n') {
temp += ch;
}
else if(ch == ' ') {
arr.emplace_back(temp);
temp.clear();
}
else {
arr.emplace_back(temp);
break;
}
}
for(string str : arr) {
cout << str <<endl;
}
return 0;
}
运行结果(第一行为输入,回车后,其余行为输出):
abc def ghi
abc
def
ghi
第二种方法:使用cin>>temp(将字符串保存到一个临时变量,并复制到数组中)、使用cin.get()循环检查在输入一个字符串之后是否输入换行结束,代码如下所示
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> arr;
string temp;
char ch;
while(cin >> temp) {
arr.emplace_back(temp);
if((ch = cin.get()) == '\n') {
break;
}
}
for(string str : arr) {
cout << str <<endl;
}
return 0;
}
运行结果(第一行为输入,回车后,其余行为输出):
abc def ghi
abc
def
ghi