0

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

我已经知道我在这里的某个地方有两个不同的缺陷。我强烈怀疑,至少有一个是逻辑问题。第一个问题是它第一次运行良好,但是当循环启动时,它不会要求用户输入新行来测试回文,它只是重新测试旧行。第二个问题是,我认为,它正在测试空间,我基于这样一个事实,即它让“汉娜”回归良好,但“从不偶数或奇数”回归糟糕。这个我只是不知道如何解决。

#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!\n\n";
      else
        cout << "Sorry, but this is not a palindrone.\n\n";

      palindroneCheck.clear();

      char repeat;
      cout << "Would you like to try another line? Y/N\n";
      cin >> repeat;
      if (repeat == "n" || repeat == "N")
        repeater = false;
    } while (repeater == true);

}
4

2 回答 2

1

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

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

为什么?因为它问,你输入'n'然后'输入'

cin >> repeat唯一读取'n',而不是'enter '

所以下次你执行“readline(cin,PalindromCheck)”时,它会读取一个空字符串。

试着palindromCheck在读完之后再写。你会看到的。

于 2013-09-27T01:28:25.947 回答
0

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

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

然后你palindroneCheckWithoutSpaces用来做 Palindrone 测试。

  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!\n\n";
  else
    cout << "Sorry, but this is not a palindrone.\n\n";

(您需要algorithm使用标头remove

更新:

std::remove根据您传入的值,从输入范围中删除一个元素(此处由 begin 和 end 定义),这里是空格' '。然后它返回更改范围的新端(因为你删除了一些东西,范围变小了)。新范围以 begin 开始,以返回值结束。

所以第二行你根据新的范围创建一个新的字符串。

于 2013-09-27T01:43:39.090 回答