字符串检查总是返回假的Palidrome
String check always returns false Palidrome
我正在编写一个程序来检查用户的输入字符串是否是回文 我的程序总是返回 false,即使字符串是已知的回文。 我认为我的问题在于回文检查器函数,因为这总是将主函数中的答案变量设置为 false。但是,我不确定为什么总是这样。
#include "stdafx.h"
#include <iostream>
#include <String>
using namespace std;
char ReadPalIn(string Pal, int len)//converts the string into a char array
{
char PalIn[100];
if (len > 100)
{
cout << "ERROR: Palindrome possibliity too big" << endl;
system("Pause");
}
else
{
for (int i = 0; i < len; i++)
{
PalIn[i] = Pal[i];
}
}
return *PalIn;
}
bool PalindromeChecker(char Pal[],int start, int end)//checks recursively if a string is a palidrome
{
if (start == end)
{
return true; //since there is only one character
}
else if (Pal[start] != Pal[end])
{
//cout << "hi" << endl;
return false;//since that will be the case that decides when something stops being a palidrome
}
else if (start < end + 1)
{
//cout << "hi" << endl;
return PalindromeChecker(Pal, start++, end--);//since we checked both the first and last characters of the char array for palandrominess. <- word of the year?
}
else
{
return true;//base case is the string is a palindrome
}
}
int main()//test if a word is a palidrome using the functions
{
int lengthOfPal = 0;
string PalInd = "abba";
bool Answer = true;
cout << "Hello what string would you like to check?" << endl;
getline(cin, PalInd);
lengthOfPal = PalInd.length();
cout << "You input is: " << PalInd << endl;
cout << "Its Length is: " << lengthOfPal << endl;
system("Pause");
char PalIn[100] = { ReadPalIn(PalInd, lengthOfPal) };
Answer = PalindromeChecker(PalIn, 0, lengthOfPal);
if (Answer == true)
{
cout << PalInd << ": is a palidrome" << endl;
system("Pause");
}
else if(Answer == false)
{
//cout << "hi" << endl;
cout << PalInd << ": is not a palidrome" << endl;
system("Pause");
}
return 0;
}
你总是返回false
因为你没有比较你认为你在比较的东西。
在最初调用PalindromeChecker()
时,您使用lengthOfPal
作为end
参数。由于字符串的索引为零,因此初始调用应使用lengthOfPal - 1
。
假设您的字符串是abba
.a
字符位于[0]
和[s.length() - 1]
(索引[3]
(。
您最终会遇到的另一个问题是将start++
和end--
作为递归调用中的参数传递。这些是后递增和后递减运算符,这意味着它将start
和end
的当前值传递到递归调用中,然后调整它们的值。由于您已将函数设置为递归,因此它每次都会对start
和end
使用相同的值。请改用前递增++start
和前递减--end
来避免此问题。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- 字符串检查总是返回假的Palidrome