c-Strcmp返回值不正确



这让我抓狂,我在测试程序中以类似的方式只对主函数进行了几次测试,一切都如预期一样,但在我编写的测试程序中比较这些答案时,即使字符串看起来相等,我也总是收到-1的返回值!

void TraverseList(LinkedList *inList)
{
    int compareTest;
    char userAnswer[64];
    char string1[64];
    char string2[64];
    for (inList->curr = inList-> head; inList->curr != NULL; inList->curr = inList->curr->next)
    {
        printf("%s", inList->curr->stringQuestion);
        scanf("%s", userAnswer);
        strcpy(string1, userAnswer);
        strcpy(string2, inList->curr->stringAnswer);
        compareTest = strcmp(string1, string2);
        printf("%sn", string1);
        printf("%sn", string2);
        printf("Return value of strcmp: %dn", compareTest);

        if(compareTest == 0)
        {
            printf("Correct!n");
        }
        else
        {
            printf("Incorrect!n");
        }
    }
    printf("n");
}

当前输出示例:

How many hours are in a day? 24
24 // this is string1
24 // this is string2
Return value of strcmp: -1
Incorrect!

当您担心在使用字符串时没有得到正确的结果时,在变量的打印输出周围放置一些识别标记是一个好习惯。

printf("X%sXn", variable);

这将向您展示计算机真正在测试什么。

此外,如果你发现这对你不起作用,你可以尝试打印字符串中的各个字符及其ascii值,以防有像"\a"这样的隐藏字符。

for(x=0; x<strlen(string_variable); x++)
    printf("'%c' = %dn", string_variable[x], string_variable[x]);

最新更新