首先,我非常感谢您愿意提供的任何帮助。我是C ++的新手,并且一直在搜索这个网站以及其他资源来解决我的问题。
此外,这确实是家庭作业的一部分。但是,分配已经转入(令人沮丧的是,没有让此代码工作)。能够解释我的特定代码中的问题是什么以及如何修复当前代码,而不是使用不同的方法来解决问题,这将是很好的解释。我当然在这个精彩的网站上找到了很多解决这个问题的方法!
我的代码没有错误,但是反转输出没有显示反转的字符数组。这导致我的小程序总是显示“你的字符串不是回文!:(”无论输入是什么。
#include <iostream>
#include <string>
using namespace std;
int isPalindrome(char *input, char *input2);
char reverseString(char *input);
int main ()
{
char input[50];
char input2[50];
cout << "Please enter a string of characters no larger than 50." << endl;
cin.getline(input, 50);
reverseString(input);
cout << "The reversed string is " << input2 << endl;
int result;
result = isPalindrome(input, input2);
if(result == 0)
cout << "Your string is a palindrome!" << endl;
else
cout << "Your string is not a palindrome! :( " << endl;
return 0;
}
int isPalindrome(char* first, char* second)
{
if (*first == *second)
return 0;
else
return 1;
}
char reverseString(char* input2)
{
int size = sizeof(input2);
for (int i = 0; i < (size/2); i ++)
swap(input2[i], input2[size-i-1]);
return *input2;
}
同样,我感谢您提供的任何帮助!如果这是一个我忽略的简单错误并且应该能够在其他地方找到,我道歉。
答案 0 :(得分:0)
检查回文并不需要花费太多精力。
bool isPalindrome(const char* s) // this function is self-contained.
{ // the caller does not need to provide
size_t n = strlen(s); // any pre-computed value.
if (n == 0)
return false;
const char* e = s + n - 1;
while (s < e)
if (*s++ != *e--)
return false;
return true;
}
int main ()
{
char input[50];
cout << "Please enter a string of characters no larger than 50." << endl;
cin.getline(input, 50);
bool result = isPalindrome(input);
cout << "Your string is"
<< ((result) ? " " : " not ")
<< "a palindrome!\n";
return (result) ? 1 : 0;
}
在你的reverseString函数中:
char reverseString(char* input2)
{
int size = sizeof(input2); // <-- ?? sizeof(char*) != strlen(input2)
size_t size = strlen(input2); // <-- should read.
for (int i = 0; i < (size/2); i ++)
swap(input2[i], input2[size-i-1]);
return *input2; // what's this? returning first char? why?
}