我寫了一個程序,用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