代码之家  ›  专栏  ›  技术社区  ›  juan

strcmp不工作

  •  7
  • juan  · 技术社区  · 15 年前

    我知道这可能是一个全新的问题(我很久没有接触过C了),但是有人能告诉我为什么这不起作用吗?

    printf("Enter command: ");
    bzero(buffer,256);
    fgets(buffer,255,stdin);
    
    if (strcmp(buffer, "exit") == 0)
        return 0;
    

    有什么建议吗?

    5 回复  |  直到 15 年前
        1
  •  27
  •   poundifdef    15 年前

    您要执行以下操作:

    strcmp(buffer, "exit\n")

    也就是说,当您输入字符串并按“enter”键时,换行符将成为 buffer .

    或者,使用strncmp(),它只比较字符串的n个字符

        2
  •  9
  •   Dave    15 年前

    fgets()返回字符串“exit\n”——与get()不同,它保留换行符。

        3
  •  6
  •   RBerteig Keith Adler    15 年前

    正如其他人所说,与 "exit" 失败是因为 fgets() 在缓冲区中包含换行符。它的保证之一是缓冲区将以换行结束,除非输入的行对于缓冲区来说太长,在这种情况下,它不会以换行结束。 还要保证缓冲区是nul终止的,所以您不需要将256字节归零,只需要让 使用255获得该保证。

    比较的简单答案是准确的 "exit\n" 出口 命令,但通常可能是用户烦恼的来源。

    strncmp() 可能允许 "exited" , "exit42" ,以及更多您可能不需要的匹配项。这可能会对您不利,尤其是当某些有效命令是其他有效命令的前缀字符串时。

    在一般情况下,最好将I/O、标记化、解析和操作分离到各自的阶段。

        4
  •  1
  •   Jonathan Adelson    15 年前

    同意戴夫的观点。此外,您可能希望改用strncmp()。然后可以设置比较的长度。

    http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

    http://www.cplusplus.com/reference/clibrary/cstring/strncmp/

        5
  •  0
  •   Phone Guy    15 年前

    我建议您将\n从字符串的末尾剥离,如下所示。

    char buf[256];
    int len;
    /* get the string, being sure to leave room for a null byte */
    if ( fgets(buf,sizeof(buf) - 1) == EOF )
    {
      printf("error\n");
      exit(1);
    }
    /* absolutely always null-terminate, the easy way */
    buf[sizeof(buf) - 1] = '\0';
    /* compute the length, and truncate the \n if any */
    len = strlen(buf);
    while ( len > 0 && buf[len - 1] == '\n' )
    {
      buf[len - 1] = '\0';
      --len;
    }
    

    这样,如果必须将输入的字符串与几个常量进行比较,则不必将\n添加到所有常量中。