为什么字符串不相等?

|
#include \"usefunc.h\"
#define MY_SIZE 256

int inpArr(char tmp[], int size) {
    size = -1;
    while(1) {
        size++;
        if((tmp[size] = getchar()) == \'\\n\') break;
    }
    return size;
}

void revString(char tmp[], int size, char new[]) {
    int i, j;
    for (i = size, j = 0; i >= 0; i--, j++) new[j] = tmp[i];
}

void copy_forw(char tmp[], int size, char new[], int offset) {
    int i, j;
    for (i = offset, j = 0; i <= size; i++, j++) new[j] = tmp[i];
}

void copy_back(char tmp[], int size, char new[], int offset) {
    int i, j;
    for (i = size-offset, j = size; i > -1; i--, j--) new[j] = tmp[i];
}

void cut(char tmp[], int size, char new[]) {

}

int main () {
    char tmp[MY_SIZE] = {0x0}, rev[MY_SIZE] = {0x0}, new[MY_SIZE] = {0x0}, some[MY_SIZE-1];
    int size = inpArr(tmp, size);
    revString(tmp, size, rev);
    copy_forw(rev, size, new, 1); copy_back(tmp, size, some, 1);
    printf(\"|%s|\\n|%s|\\n\", some, new);
    int is_palindrome = StringEqual(new, some);
    printf(\"%d\\n\", is_palindrome);
}
StringEqual几乎是一个仅逐字符比较char数组的函数。 如果输入字符串
yay
,它应该是回文,但似乎不是。为什么是这样?     
已邀请:
您的问题在于行:
if((tmp[size] = getchar()) == \'\\n\') break;
即使用户输入了“ 3”字符来表示已完成输入操作,此行仍将始终将用户输入的字符分配给数组。因此,例如,当您输入\“ yay \”,然后输入换行符来表示已完成时,您的数组如下所示:
{\'y\', \'a\', \'y\', \'\\n\'}
该数组的相反是:
{\'\\n\', \'y\', \'a\', \'y\'}
...这显然会使回文检查失败。我建议修改您的代码,如下所示:
int inpArr(char tmp[], int size) {
    size = -1;
    while(1) {
        size++;
        if((tmp[size] = getchar()) == \'\\n\') break;
    }
    tmp[size] = \'\\0\';  //replace the newline with a null terminator
    return size;
}

void revString(char tmp[], int size, char new[]) {
    int i, j;
    for (i = size - 1, j = 0; i >= 0; i--, j++) new[j] = tmp[i];
    new[size] = \'\\0\';  //place a null terminator at the end of the reversed string
}
    
看行:
if((tmp[size] = getchar()) == \'\\n\') break;
\'\\n\'
总是出现在字符串的末尾。那是你的问题。     

要回复问题请先登录注册