我正在使用 fgets 和 stdin 来读取一些数据,我读取的最大长度为 25。通过我在此代码上运行的测试之一,我想要的数据后面有几百个空格 - 其中导致程序失败。
有人可以建议我在使用 fgets 时如何忽略所有这些额外的空格并转到下一行吗?
反复使用fgets()
,然后扫描字符串看是否全是空格(以及是否以换行符结尾),如果是则忽略。还是使用getc()
orgetchar()
在循环中代替?
char buffer[26];
while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
...process the first 25 characters...
int c;
while ((c = getchar()) != EOF && c != '\n')
;
}
该代码只是忽略了直到下一个换行符的所有字符。如果要确保它们是空格,请在(内部)循环中添加一个测试 - 但是如果字符不是空格,您必须决定要做什么。
详细说明 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
}
...
}
编辑:啊,乔纳森写 C 比我快。:)
试试这个代码,删除尾随空格。
char str[100] ;
int i ;
fgets ( str , 80 , stdin ) ;
for ( i=strlen(str) ; i>0 ; i-- )
{
if ( str[i] != ' ' )
{
str[i+1]='\0';
break ;
}
}