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

使用fgets时忽略多余的空格

  •  3
  • Gary  · 技术社区  · 16 年前

    我使用fgets和stdin来读取一些数据,其中我读取的最大长度为25。在我对这段代码运行的一个测试中,我想要的数据后面有几百个空格,这会导致程序失败。

    有人能告诉我在使用fgets时如何忽略所有这些额外的空间并转到下一行吗?

    3 回复  |  直到 16 年前
        1
  •  2
  •   Jonathan Leffler    16 年前

    使用 fgets() 以迭代方式,然后扫描字符串以查看它是否是所有空格(以及是否以换行符结尾),如果是,则忽略它。或使用 getc() 或 getchar() 而是一个循环?

    char buffer[26];
    
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        ...process the first 25 characters...
        int c;
        while ((c = getchar()) != EOF && c != '\n')
            ;
    }
    

    这段代码只是忽略了下一个换行符之前的所有字符。如果要确保它们是空格,请在(内部)循环中添加一个测试-但如果角色不是空格,则必须决定如何操作。

        2
  •  0
  •   Paul Tillotson    16 年前

    阐述jonathan leffler关于getc()的建议:

    我假设你有一个这样的循环:

    while (!feof(stdin)) {
      fgets(buf, 25, stdin);
      ...
    }
    

    改成这样:

    while (!feof(stdin)) {
      int read = fgets(buf, 27, stdin);
      if (read > 26) { // the line was *at least* as long as the buffer
        while ('\n' != getc()); // discard everything until the newline character
      }
      ...
    }
    

    编辑:啊,乔纳森写得比我快。

        3
  •  0
  •   Pavunkumar    16 年前

    请尝试以下代码,以删除尾随空格。

     char str[100] ;
        int i ;
        fgets ( str , 80 , stdin ) ;
        for ( i=strlen(str) ; i>0 ; i-- )
        {
                if ( str[i] != ' ' )
                {
                        str[i+1]='\0';
                        break ;
                }
        }