我正在尝试使用我在python中学到的东西在C中做一个回文检查...(我是这里的新手)。 回文检查器从文件中获取输入,直到它读取文件的位置,那里没有问题,但我不确定输出是否表示所有单词(来自输入文件)的确切问题不是回文.....
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void palinChecker(char *input);
void main()
{
FILE *fp;
char buff[255];
fp = fopen("input.txt", "r");
if( fp != NULL ){
while ( !feof(fp ) ){
memset(buff, '\0', sizeof( buff) );
fgets(buff, 255, (FILE*)fp);
palinChecker(buff);
}
fclose(fp);
}
}
void palinChecker(char *input){
int i, index=0;
char letter;
char rev[255];
size_t length = strlen(input);
int n = length-2;
while(index<n){
letter = input[n-1];
rev[index] = letter;
index = index + 1;
n = n - 1;
}
if(rev == input){
printf("%s is a palindrome\n", input);
}
else{
printf("%s is not a palindrome\n", input);
}
}
请我不知道为什么结果如此...... 结果:
ABA 不是回文
ABA 不是回文
kanakanak 不是回文
KANAKANAK 不是回文
11 不是回文
ZZ 不是回文
12321 不是回文
012345678909876543210 不是回文
abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba 不是回文
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll不是回文结构
升 不是回文
计算机 不是回文
科学 不是回文
阿巴 不是回文
Kanakanak 不是回文
123 不是回文
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll不是回文结构
l不是回文
答案 0 :(得分:1)
除了在C中,你不能将字符串与==进行比较(你必须使用strcmp),你的算法有一个缺陷。让我们在input =“aba”的情况下走下去:
void palinChecker(char *input){ // "aba"
int i, index=0;
char letter;
char rev[255];
size_t length = strlen(input); // 3
int n = length-2; // 1
while(index<n){ // index = 0 in the beginning, n = 1
letter = input[n-1]; // letter = input[0] = 'a'
rev[index] = letter; // rev[0] = 'a'
index = index + 1; // index = 1
n = n - 1; // n = 0
} // ...and we get out of the cycle
if(rev == input){ // rev = "a" (not 0-terminated), input = "aba"
printf("%s is a palindrome\n", input);
}
else{
printf("%s is not a palindrome\n", input);
}
}
答案 1 :(得分:0)
如上所述,您使用相等运算符(==)来比较2个字符串。这是错误的,因为在C中,字符串存储为字符数组。字符串的名称是指向该数组的第一个元素的指针(指针是一个具有内存地址作为值的变量)。因此,在C中,指定字符串的变量不包含有关字符串的任何数据,这与python不同。因此,当您进行比较时,您基本上比较了2个内存地址。由于存在2个不同的字符串,存储在不同的地方,所以相等性总是为假。
为避免这种情况,C标准库提供了strcmp函数(在strings.h中)。传递要作为参数进行比较的字符串,如果第一个字符串更大则结果为正,如果第一个字符串更小则结果为负,如果字符串相等则结果为0.