【问题标题】:C++ Same Letter Consecutively ProgramC++同一个字母连续编程
【发布时间】:2014-12-03 00:42:24
【问题描述】:

我正在尝试使用字符串编写程序来确定文件中的单词是否连续包含两个相同的字母。我为此编写了一个函数:

bool likeornot(apstring word)
{
for (int i = 0; i < word.length(); i++)
{
    if (toupper(word[i]) != toupper(word[i + 1]))
        return false;
}
return true;

}

主代码:

while(!fin.eof())
{
    fin >> word;
    if (likeornot(word))
        cout << "I like " << word << "." << endl;
    else
        cout << "I don't like " << word << "." << endl;
}
fin.close();

这总是返回 false 并告诉我它不喜欢任何单词,如果有人能帮我弄清楚为什么那会很棒。

【问题讨论】:

  • 你应该在使用fin &gt;&gt; word;之后的值之前测试读取是否成功。
  • 是的,我知道了,如果文件没有打开,程序就会终止。
  • 即使在打开文件后(例如,达到 eof 时)读取文件也可能失败。您应该在每次从流中读取后测试结果。

标签: c++ string function


【解决方案1】:

更像

for (int i = 0; i < word.length() - 1; i++)
{
     if (toupper(word[i]) == toupper(word[i + 1]))
          return true;
}
return false;

【讨论】:

  • 您可以通过将最后读取的值保存在寄存器中来进一步优化这一点。 :p
【解决方案2】:

改变

for (int i = 0; i < word.length(); i++)
{
    if (toupper(word[i]) != toupper(word[i + 1]))
        return false;
}

for (int i = 0; i < word.length() - 1; i++)
{
    if (toupper(word[i]) != toupper(word[i + 1]))
        return false;
}

在循环中的最后一次比较中,您将超出字符串。

【讨论】:

    【解决方案3】:

    您的循环需要以 word.length()-1 结束,而不是 word.length() 在此版本中,您总是将单词的最后一个字符与字符串末尾的字符进行比较,大概是空终止符。

    【讨论】:

      【解决方案4】:

      您正在阅读超出字符串末尾的内容,但由于此错误,您不太可能达到那么远:

      if (toupper(word[i]) != toupper(word[i + 1]))
        return false;
      

      如果前两个字母不一致,函数返回false

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-08
        • 2021-06-26
        • 1970-01-01
        • 2017-04-25
        • 2016-09-02
        • 2018-07-13
        • 2023-03-22
        相关资源
        最近更新 更多