C++ (1) 为什么它不承认这是一个回文&;(2) 如何让它打印带有空格的原始输入?
我找遍了所有地方试图回答我自己的问题,但我遇到了麻烦。我已经在做同样的练习三天了,并且感到很沮丧,因此我写了第一篇文章!这是一项学校作业,但我真的想了解为什么这不起作用。当我使用输入“bob”时,它会像预期的那样返回“bob是一个回文”。当我输入“bobby”时,它会像预期的那样返回“bobby不是回文”。那里一切都好。当我使用“从不奇数或偶数”这句话时,我花了很长时间才想出如何从输入中删除空格,但我也成功地做到了这一点。但问题是:(1)即使删除了空格,似乎也认为“Neverodoveren”不是回文——为什么?我错过了什么?此外,这可能是一个愚蠢的问题(但这是我第一次尝试编程,我是一个十足的新手),在我删除最终输出中的空格之前,如何让它输出原始用户输入?目前,下面的代码输出“NeverodReven不是回文”。提前谢谢你给我的任何建议C++ (1) 为什么它不承认这是一个回文&;(2) 如何让它打印带有空格的原始输入?,c++,palindrome,removing-whitespace,C++,Palindrome,Removing Whitespace,我找遍了所有地方试图回答我自己的问题,但我遇到了麻烦。我已经在做同样的练习三天了,并且感到很沮丧,因此我写了第一篇文章!这是一项学校作业,但我真的想了解为什么这不起作用。当我使用输入“bob”时,它会像预期的那样返回“bob是一个回文”。当我输入“bobby”时,它会像预期的那样返回“bobby不是回文”。那里一切都好。当我使用“从不奇数或偶数”这句话时,我花了很长时间才想出如何从输入中删除空格,但我也成功地做到了这一点。但问题是:(1)即使删除了空格,似乎也认为“Neverodoveren”不
#include <string>
#include <cctype>
using namespace std;
int main() {
string userInput;
int startInput;
bool isPalindrome = true;
getline (cin, userInput);
startInput = userInput.length();
for(int i = 0; i<userInput.length(); i++)
if(userInput[i] == ' ') userInput.erase(i,1);
for (int i = 0; i<(startInput / 2); i++){
if (userInput[i] != userInput[(startInput -1 ) -i])
isPalindrome = false;
}
if (isPalindrome){
cout << userInput << " is a palindrome" << endl;
}
else {
cout << userInput << " is not a palindrome" << endl;
}
return 0;
}
#包括
#包括
使用名称空间std;
int main(){
字符串用户输入;
int startInput;
bool isPalindrome=true;
getline(cin,userInput);
startInput=userInput.length();
对于(int i=0;i在删除所有空格后,startInput
不再引用字符串的实际长度。这意味着此比较:
if (userInput[i] != userInput[(startInput -1 ) -i])
未比较正确的字符
您可以通过添加以下行来解决此问题:
startInput = userInput.length();
在完成擦除之后
这是一个例子
另外,在您的擦除代码中,正如其他人指出的那样,这个比较i,问题在于startInput
没有考虑到您擦除了一些空格。因此,将行startInput=userInput.length();
移动到擦除循环之后
不改变原始输入的替代解决方案可以是:
#include <iostream>
#include <string>
int main()
{
std::string userInput;
std::string userInputNoSpace; // Use one more string
int startInput;
bool isPalindrome = true;
std::getline(std::cin, userInput);
// Copy all characters that are NOT space to the new string
for (auto c : userInput)
{
if (c != ' ')
{
userInputNoSpace += c;
}
}
startInput = userInputNoSpace.length();
for (int i = 0; i<(startInput / 2); i++)
{
if (userInputNoSpace[i] != userInputNoSpace[(startInput -1 ) -i])
{
isPalindrome = false;
break;
}
}
if (isPalindrome)
{
std::cout << userInput << " is a palindrome" << std::endl;
}
else
{
std::cout << userInput << " is not a palindrome" << std::endl;
}
return 0;
}
输出:
never odd or even is a palindrome
我建议您尝试在调试器中逐个语句地检查代码语句,同时监视变量及其值。我特别认为,对于包含两个连续空格的输入,您需要这样做。并考虑返回的内容。啊,是的,您忘记了减少startInput
,如果字符串包含空格,则应该减少工作正常(代码过于复杂).只需创建一个没有空格的字符串,您就完成了。好吧,我让它认识到NeverodReven是一个回文。谢谢!但我如何让它用空格打印原始输入?在修改值之前创建一个副本。或者最好提取一个函数。请原谅我的无知,但为什么不想比较有符号值和无符号值?看到这个吗。最好避免这些东西:)谢谢。auto c在这里到底做什么?我不熟悉。我只花了几个星期的时间从零知识学习编程,所以如果这是一个愚蠢的问题,我很抱歉。@krystenr1auto c
这里与char c
相同。它一次通过字符串一个字符。就像“对于字符串userInput中的每个字符c”
never odd or even
never odd or even is a palindrome