gpt4 book ai didi

c++ - 编写一个程序,读取一串字符并调用递归函数来确定字符串中的字母是否构成回文

转载 作者:行者123 更新时间:2023-12-04 14:36:41 24 4
gpt4 key购买 nike

我的任务是编写一个递归函数来确定用户输入的字符串是否为回文。我认为我有一个非常强大的代码基础来解决这个问题,但它似乎并没有像我想要的那样工作。
我正在做一些故障排除以找出问题所在,看起来如果我的字符串 <= 8 个字符长,数组的长度出于某种原因自动变为 14。可以使用比我更擅长 C++ 的人的一些故障排除和输入。
这是我的代码:

#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

bool isPalindrome(char[], int, int);

int main()
{
char palin[100],
lowerPalin[100];

cout << "Enter a line that might be a palindrome:" << endl;
cin.get(palin, 100);

for (int i = 0, x = 0; i < strlen(palin); i++) // this for loop will remove punctuation, white space and make it all lowercase
{
if((palin[i] != ' ') && (ispunct(palin[i]) == false))
{
lowerPalin[x] = tolower(palin[i]); // transfering inputted array into new array with just alpha characters
x++;
}
}

int low = 0,
high = strlen(lowerPalin);

if (isPalindrome(lowerPalin, low, high))
cout << "The string is a palindrome." << endl;
else
cout << "The string is NOT a palindrome." << endl;

return 0;
}

bool isPalindrome(char lowerPalin[], int low, int high)
{
if (lowerPalin[low] == lowerPalin[high])
return isPalindrome(lowerPalin, low + 1, high - 1);

if (lowerPalin[low] != lowerPalin[high])
return false;

return true;
}
我还在努力学习递归,所以如果我的底部函数有任何问题,请告诉我。
编辑:谢谢大家的帮助!感谢大家,我能够理解并纠正我的错误。也感谢您回答中的所有提示,它对像我这样的新学生有很大帮助!

最佳答案

if anything is wrong with my bottom function please let me know.


如果 high,您需要终止递归低于 low .
正如所写的,在回文的情况下,你会在你的 lowerPalin 上越界。
更新:
正如@user4581301 在下面评论的那样(并回答您上面的问题),您需要零终止您的 lowerPalinpalin 填充后.否则, strlen将寻找那个 0在未初始化的数组中;它可能会在位置 14 找到它(发生在你身上)或根本没有。这可能会导致访问冲突异常!

关于c++ - 编写一个程序,读取一串字符并调用递归函数来确定字符串中的字母是否构成回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69110725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com