为什么我不能比较这两个字符串?字符串输入相同,但总是 return false

Why can't i compare this two string ? The string input is the same, but it always return false

我从这里得到了随机密码生成程序https://codereview.stackexchange.com/questions/138703/simple-random-password-generator 然后我想做一个简单的密码程序。它生成 3 个随机字符并使用 sprint 将 "REG-" 与 3 个随机字符组合。

REG-xxx

但是程序没有按照我期望的方式进行比较。我是否遗漏了数组中的一些意想不到的元素?因为我读过 char 数组也将换行符或 space 视为其元素,所以在此先感谢。 这是我的代码

#include<stdio.h>
#include<string.h>
#include<time.h>

int main(){

    int i;
    srand((unsigned int)(time(NULL)));
    char pass[6];
    char codebook[10];
    char password[10];

    printf("Press enter to get a three-character password\n");
    getchar();

    for (i = 0; i < 1; i++) {
        pass[i] = rand() % 9;
        char capLetter = 'A' + (rand() % 26);
        pass[i + 2] = capLetter;
        char letter = 'a' + (rand() % 26);
        pass[i + 3] = letter;
        printf("%d%c%c\n", pass[i], pass[i + 2], pass[i + 3]);
        sprintf(codebook, "REG-%d%c%c\n", pass[i], pass[i+2], pass[i + 3]);
    }
    system("pause");
    printf("%s\n", codebook);
    fflush(stdin);
    printf("Enter the password: ");
    scanf("%s", password);
    printf("\n%s\n", password);
    printf("%s\n", codebook);
    system("pause");
    if(strcmp(codebook , password) == 0){
        printf("password is correct\n");
    } else{
        printf("password is false\n");
    }


    return 0;
}

在这里你在密码中打印一个换行符

sprintf(codebook, "REG-%d%c%c\n", pass[i], pass[i+2], pass[i + 3]);

您以后不能在密码中输入该换行符,因此比较失败。

更改为

sprintf(codebook, "REG-%d%c%c", pass[i], pass[i+2], pass[i + 3]);

解决问题。

要找到这种字符串中的空格问题,我建议通过打印 "impossible" 但可打印字符中的字符串来调试。正如我在评论中推荐的那样,我通过引入一些额外的印刷品(或修改现有印刷品)发现了问题:

在这种情况下,有帮助的直接在有问题的之后 sprintf():

printf("#%s#\n", codebook);