c++ - 拆分句子并放置在 vector 中

标签 c++

我的教授给了我一个需要多行输入的代码。我目前正在更改我们当前任务的代码,我遇到了一个问题。该代码旨在获取输入字符串并将它们从句点分成句子,然后将这些字符串放入一个 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/

相关文章:

c++ - Visual Studio 等中datatype&const var_name 的实现差异

c++ - 跳过 for 循环的特定(指定)迭代

c++ - 正则表达式匹配需要永远

C++ 与在线 SQL 数据库交互?

c++ - 声明模板类型未知的元组

c++ - 检查 std::any 变量是否包含 std::string 时出现问题

c++ - boost::serialization 反序列化 xml_archive 异常

c++ - 在 C++ 中通过子类访问父类(super class)的 protected 静态成员

c++ - 将标志组合映射到枚举的最简单方法是什么?

c++ - 通过网络(远程屏幕广播应用程序)传输 JPEG 压缩的屏幕图 block 时,是否值得/推荐使用 zlib(或类似的)压缩?