回文测试仪存在逻辑缺陷
Palindrome tester has logic flaws
这只是我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 开头,以返回值结束。
因此,第二行您根据新范围创建一个新字符串。
相关文章:
- C++模板来检查友元函数的存在
- 既然存在危险,为什么项目要使用-I include开关
- 我们可以访问一个不存在的联盟的成员吗
- C++:对不存在的命名空间使用命名空间指令
- C++quit()函数中可能存在作用域问题
- C++擦除(如果存在)
- g++ 说函数不存在,即使包含正确的标头
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 有了gcc,是否可以链接库,但前提是它存在
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 这个危险指针示例是否因为 ABA 问题而存在缺陷?
- clang实现char8_t的方式是否存在缺陷,或者标准的某个黑暗角落是否禁止优化?
- 可以归类为病毒的程序可能存在安全缺陷
- trie搜索中存在逻辑缺陷
- 回文测试仪存在逻辑缺陷
- mingw中存在奇怪的语法缺陷
- 指针上的interpret_cast在char和unsigned char之间存在缺陷
- 将模拟集中在[0.5,0.5,0.5]中,盒大小为1是否存在缺陷?
- 在多态对象上使用static_cast是否表明存在设计缺陷?
- 为什么没有<stlfwd>标题,不存在它是否可以被视为缺陷?