【问题标题】:String compare in c with fgets [duplicate]c中的字符串与fgets比较[重复]
【发布时间】:2016-12-20 23:24:40
【问题描述】:

这只是我刚刚写的一个简单的代码,我不明白为什么当我在流中输入母亲时它不会给我真实的信息。当他们相互比较时,这对我来说是合乎逻辑的,它必须是相同的还是?
这是我的简单代码:

 char string[20];
 fgets(string,20,stdin);

 printf("%s",string);

 if(strcmp(string,"mother")==0)
 {
   printf("they are the same");
 }
 else
 {
     printf("they are not");
 }

我也试过

 if(string =="mother")
 \\do something

但它不会只是给我真实的人可以帮助我

【问题讨论】:

  • fgets 不比较字符串。对于strcmp如何 创建字符串并不重要。还有你不明白的函数文档怎么办?
  • 试试printf("<%s>\n",string); 看看你在用fgets()读什么。
  • strcmp(string,"mother\n")

标签: c


【解决方案1】:
 if(string =="mother")  // won't work

您不能直接将 C 字符串与 == 进行比较。改用标准库函数strcmp

if( 0 == strcmp(string, "mother") )
{
    printf( "equal" );
}

您还需要从fgets 中删除\n,否则字符串比较将被视为错误。

fgets(string,20,stdin);
string[strcspn(string, "\n")] = 0;   // without this, `strcmp` would return false

【讨论】:

    【解决方案2】:

    正如其他人所说,您无法将字符串与== 进行比较。为了使您的代码正常工作,您需要去除从fgets() 附加的\n 字符。否则,您正在比较:

    if (strcmp("mother\n", "mother") == 0) {
    

    除非您删除 \n 字符,否则这始终是错误的。

    由于fgets() 在读取用户输入时如果不成功会返回NULL,因此也可以安全地进行检查,如下所示:

    if (fgets(string, 20, stdin) == NULL) {
        /* Exit program */
    }
    

    还可以为fgets()添加一些额外的错误检查,比如检查缓冲区溢出,可以这样检查:

    slen = strlen(string);
    if (slen > 0) {
        if (string[slen-1] == '\n') {
            string[slen-1] = '\0';
        } else {
            /* Exit program */
        }
    }
    

    经过这些考虑,您的代码可能如下所示:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define BUFFSIZE 20
    
    int
    main(int argc, char *argv[]) {
        char string[BUFFSIZE];
        size_t slen;
        const char *compare = "mother";
    
        printf("Enter a string: ");
        if (fgets(string, BUFFSIZE, stdin) == NULL) {
            printf("Error reading string into buffer.\n");
            exit(EXIT_FAILURE);
        }
    
        slen = strlen(string);
        if (slen > 0) {
            if (string[slen-1] == '\n') {
                string[slen-1] = '\0';
            } else {
                printf("Buffer overflow. Exceeded buffer size of %d.\n", BUFFSIZE);
                exit(EXIT_FAILURE);
            }
        } 
    
        if (!*string) {
            printf("No string entered.\n");
            exit(EXIT_FAILURE);
        }
    
        printf("My string = %s.\n", string);
        if (strcmp(string, compare) == 0) {
            printf("They are the same.\n");
        } else {
            printf("They are not the same.\n");
        }
    
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      来自fgets() 的手册页:

      fgets()  reads in at most one less than size characters from stream and
      stores them into the buffer pointed to by s.  Reading  stops  after  an
      EOF  or a newline.  If a newline is read, it is stored into the buffer.
      A terminating null byte ('\0') is stored after the  last  character  in
      the buffer.
      

      您是否检查过您的输入是否附加了换行符? "mother""mother\n" 不同。

      【讨论】:

        【解决方案4】:

        fgets 不会从输入中删除换行符 (\n)。您应该在比较字符串之前删除它(如果存在):

        char string[20];
        fgets(string,20,stdin);
        
        int len = strlen(string);
        // len-1 is the last character before the original \0
        if(len > 0 && string[len-1] == '\n'){
            // remove the new-line by ending the string sooner
            string[len-1] = '\0';
        }
        
        if(strcmp(string,"mother")==0)
        

        您的第二次尝试,直接使用== 比较两个字符串肯定行不通。

        【讨论】:

        • 建议if(len &gt; 1 --> if(len &gt; 0
        猜你喜欢
        • 2015-12-15
        • 2018-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-28
        • 1970-01-01
        相关资源
        最近更新 更多