为什么 strcmp 或 strncmp 不能在 C 编程语言上运行


#include <stdio.h>
#include <string.h>
int main(){
    char name[20];
    printf("Whats your name: ");
    fgets(name,20,stdin);
    printf("hello, %s", name);
    if(strcmp(name, "john")==0){
        printf("hello john.");
    }
    return 0;
}

我是一个 Java 开发人员,一个新在 C 中。 为什么 strcmp 不起作用。 请帮帮我

问题出在fgets 上。修复新行错误:

#include <stdio.h>
#include <string.h>
int fixedFgets(char str[], int n);
int main() {
    char name[20];
    printf("Whats your name: ");
    if (fixedFgets(name, 20))
    {
        printf("hello, %sn", name);
        if (strcmp(name, "john") == 0) {
            printf("hello john.");
        }
    }
    return 0;
}
/*
    Function will perform the fgets command and also remove the newline
    that might be at the end of the string - a known issue with fgets.
*/
int fixedFgets(char str[], int n)
{
    int success = 1;
    // Check that fgets worked
    if (fgets(str, n, stdin) != NULL)
    {
         str[strcspn(str, "n")] = 0;
    }
    else
    {
        success = 0;
    }
    return success;
}

最新更新