我写了一个程序,用strrev()
函数反转数组,并检查它的值是否与原始数组相匹配,即回文的种类。当这些值匹配时,它将打印Palindrome
,否则,Not a palindrome
。如何比较数组和颠倒的数组并检查它们的值是否匹配?
但是,当我比较它们,并且值不匹配时,它仍然打印Palindrome
。
下面是代码:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <string.h>
#define MAX_LEN 100
void palindrom(char string[]);
int main()
{
char string[MAX_LEN] = { 0 };
printf("Enter string (max length 100 chars): ");
fgets(string, MAX_LEN, stdin);
if(string[strlen(string)-1] == '\n') { string[strlen(string)-1] = 0; }
palindrom(string);
return (0);
}
void palindrom(char string[])
{
int check = 0;
check = strcmp(strrev(string), string);
if (check == 0)
{
printf("Palindrome");
}
else
{
printf("Not a palindrome");
}
}
什么是我的问题吗?谢谢。
您需要复印。例如。 'char * copy = strdup(string); ''check = strcmp(strrev(copy),string);'...'free(copy);' – BLUEPIXY
另外'char string [MAX_LEN] = {0};' - >'char string [MAX_LEN + 1 ] = {0};' – BLUEPIXY
@BLUEPIXY,函数:'fgets()'不会超过输入缓冲区,并且会正确地将NUL字节插入到输入缓冲区的范围内,因此不需要再使输入缓冲区比MAX_LEN – user3629249