【发布时间】:2021-02-04 18:52:59
【问题描述】:
我有一个用空格分割字符串的函数。
代码如下:
vector<string> split(string text) {
vector<string> output;
string temp;
while (text.size() > 0) {
if (text[0] == ' ') {
output.push_back(temp);
temp = "";
text.erase(0, 1);
}
else {
temp += text[0];
text.erase(0, 1);
}
}
if (temp.size() > 0) {
output.push_back(temp);
}
return output;
}
int n = 0;
int main()
{
while (1) {
cout << "Main has looped" << endl << "Input:";
string input;
cin >> input;
vector<string> out = split(input);
cout << n << ":" << out[0] << endl;
n++;
}
return 1;
}
这应该用空格分割输入,它似乎是这样做的,除了函数一次只返回一个值,并且重复这样做直到输出向量为空:
Main has looped
Input:Split this text
0:Split
Main has looped
Input:1:this
Main has looped
Input:2:text
Main has looped
Input:
出于某种原因,它似乎也跳过了输入。我不知道发生了什么,请帮忙!
【问题讨论】:
-
您的意思是在
while循环中读取输入字符串吗?