回文测试仪存在逻辑缺陷

Palindrome tester has logic flaws

本文关键字:缺陷 存在 测试仪 回文      更新时间:2023-10-16

这只是我C++课的基本回文测试器,似乎存在问题。

我已经知道我在某处有两个独立的缺陷。我强烈怀疑,至少有一个是逻辑问题。第一个问题是它第一次运行良好,但是当循环启动时,它不会要求用户输入放入新行以作为回文进行测试,它只是重新测试旧的。第二个问题是,我认为,它正在测试空间,我基于这样一个事实,即它让"hannah"恢复为好,但"从不偶数或奇数"却很糟糕。这个我只是不知道如何解决。

#include <iostream>
#include <string>
using namespace std;
int main()
{
  bool repeater = true;
  do
    {
      string palindroneCheck;
      bool palindronity = true;
      cout << "Please enter a line to test for palindromity.n";
      getline(cin, palindroneCheck);
      int stringSize = palindroneCheck.size();
      int cutOff = stringSize/2;
      for (int palindroneLength = 0; palindroneLength < cutOff; palindroneLength++)
        {
          if (palindroneCheck[palindroneLength] != palindroneCheck[stringSize - palindroneLength -1])
            {palindronity = false;
              break;}
        }
      if(palindronity == true)
        cout << "Congratulations! This line is a palindrone!nn";
      else
        cout << "Sorry, but this is not a palindrone.nn";
      palindroneCheck.clear();
      char repeat;
      cout << "Would you like to try another line? Y/Nn";
      cin >> repeat;
      if (repeat == "n" || repeat == "N")
        repeater = false;
    } while (repeater == true);
}

好的,你对空格的看法是对的。您的代码将要求空格与其他字符一样位于同一位置。

另一个错误似乎更微妙:它是你要求重复或不重复的地方。

为什么?因为它询问,所以你输入"n",然后"输入"

cin >> repeat只读取"n",而不读取"enter"

所以下次你做'readline(cin,PalindromCheck)'时,它会读取一个空字符串。

尝试在阅读后立即写palindromCheck。你会知道的。

getline 的阅读问题通过注释解决。对于空格,您可以通过删除字符串palindroneCheck中的所有空格来解决它,

std::string::iterator new_end = std::remove(palindroneCheck.begin(), palindroneCheck.end(), ' ');
std::string palindroneCheckWithoutSpaces(palindroneCheck.begin(), new_end);

然后你用palindroneCheckWithoutSpaces做回文测试。

  int stringSize = palindroneCheckWithoutSpaces.size();
  int cutOff = stringSize/2;
  for (int palindroneLength = 0; palindroneLength < cutOff; palindroneLength++)
    {
      if (palindroneCheckWithoutSpaces[palindroneLength] != palindroneCheck[stringSize - palindroneLength -1])
        {palindronity = false;
          break;}
    }
  if(palindronity == true)
    cout << "Congratulations! This line is a palindrone!nn";
  else
    cout << "Sorry, but this is not a palindrone.nn";

(您需要标头algorithm才能使用remove

更新:

std::remove根据您传入的值从输入范围中删除元素(此处由开头和结尾定义),这里是空格' '。然后它返回更改范围的新结束(由于您删除了某些内容,因此范围变小)。新范围以 begin 开头,以返回值结束。

因此,第二行您根据新范围创建一个新字符串。