使用fgets时忽略额外的空格

时间:2010-03-20 04:07:42

标签: c fgets

我正在使用带有stdin的fgets来读取一些数据,我读取的最大长度为25.我正在运行此代码的其中一个测试,我的数据之后有几百个空格想 - 导致程序失败。

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

3 个答案:

答案 0 :(得分:2)

迭代地使用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')
        ;
}

该代码只会忽略直到下一个换行符的所有字符。如果你想确保它们是空格,在(内部)循环中添加一个测试 - 但如果角色不是空格,你必须决定该怎么做。

答案 1 :(得分:0)

明白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
  }
  ...
}

编辑:啊,Jonathan比我写C更快。:)

答案 2 :(得分:0)

尝试使用此代码删除尾随空格。

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