我的教授给了我一个需要多行输入的代码。我目前正在更改我们当前任务的代码,我遇到了一个问题。该代码旨在获取输入字符串并将它们从句点分成句子,然后将这些字符串放入一个 vector 中。
vector<string> words;
string getInput() {
string s = ""; // string to return
bool cont = true; // loop control.. continue is true
while (cont){ // while continue
string l; // string to hold a line
cin >> l; // get line
char lastChar = l.at(l.size()-1);
if(lastChar=='.') {
l = l.substr(0, l.size()-1);
if(l.size()>0){
words.push_back(s);
s = "";
}
}
if (lastChar==';') { // use ';' to stop input
l = l.substr(0, l.size()-1);
if (l.size()>0)
s = s + " " + l;
cont = false; // set loop control to stop
}
else
s = s + " " + l; // add line to string to return
// add a blank space to prevent
// making a new word from last
// word in string and first word
// in line
}
return s;
}
int main()
{
cout << "Input something: ";
string s = getInput();
cout << "Your input: " << s << "\n" << endl;
for(int i=0; i<words.size(); i++){
cout << words[i] << "\n";
}
}
代码将字符串放入一个 vector 中,但将句子的最后一个词附加到下一个字符串,我似乎无法理解为什么。
最佳答案
这一行
s = s + " " + l;
将始终执行,除了输入结束,即使最后一个字符是“.”。您很可能在两个 if
之间遗漏了一个 else
。
关于c++ - 拆分句子并放置在 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28848063/