简体   繁体   English

strcmp 不适用于相同长度的相同字符串

[英]Strcmp doesn't work on same strings with same length

So, I have this code, where password is a string obtained by breaking into tokens a bigger string, and pass obtained from a text file.所以,我有这个代码,其中密码是一个字符串,它是通过将一个更大的字符串分解为令牌而获得的,并从文本文件中获得。 I even used strcspn so i can remove '\\n' from pass.我什至使用了 strcspn 所以我可以从 pass 中删除 '\\n' 。

    if (ok == 1){

        char buffer[20];
        snprintf(buffer, sizeof(buffer), "%s.txt", username);

        chdir("./passwords") ;

        FILE *userf;
        userf = fopen(buffer,"r");
        if(userf == NULL){
            perror("Eroare la fopen");
            exit(1);
        } else
            printf("Am deschis fisierul cu parola\n");

        char pass[20];

        if(fgets(pass, sizeof(pass), userf) == NULL){

            perror("Eroare la fgets");
            exit(1);
        } 
        pass [ strcspn(pass, "\r\n") ] = '\0'; 
        printf("%s\n%s\n",password, pass);
        printf("%i %i\n",strlen(password), strlen(pass));

        if(strcmp(password, pass) == 0){
            printf("Connected");
        }
    }

As you can see from the terminal it prints out the same string with the same length but strcmp for some reason doesn't return 0.I'm really confused.正如您从终端看到的那样,它打印出具有相同长度的相同字符串,但 strcmp 由于某种原因不返回 0。我真的很困惑。

在此处输入图片说明

If you add a \\n to the last printf you'll see it works fine.如果您在最后一个printf添加一个\\n ,您会看到它工作正常。

Your program is just exiting before it's flushed the stdout buffer.您的程序只是在刷新标准输出缓冲区之前退出。

How do you know it's not comparing correctly?你怎么知道它没有正确比较? If it's by the printed statement you appear to have forgotten the newline character which means it probably won't be flushed to the screen without another print.如果是打印语句,您似乎忘记了换行符,这意味着它可能不会在没有其他打印的情况下刷新到屏幕上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM