使用与fgets时忽略多余的空格 [英] ignore extra spaces when using fgets

查看:446
本文介绍了使用与fgets时忽略多余的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用与fgets:标准输入一些数据看,与最大长度我是25.我对这个code运行测试的一个阅读,有几百位后数据,我想 - 这会导致程序失败。

I'm using fgets with stdin to read in some data, with the max length I read in being 25. With one of the tests I'm running on this code, there are a few hundred spaces after the data that I want - which causes the program to fail.

有人能告诉我关于如何使用与fgets时忽略所有这些多余的空间,并转到下一行?

Can someone advise me as to how to ignore all of these extra spaces when using fgets and go to the next line?

推荐答案

使用与fgets()迭代,然后扫描线,看它是否是所有空间(以及是否它以换行符结尾),而忽略它,如果它是。或者使用 GETC()的getchar()在一个循环呢?

Use fgets() iteratively, then scan the string to see whether it is all spaces (and whether it ends with a newline) and ignore it if it is. Or use getc() or getchar() in a loop instead?

char buffer[26];

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

这code简单地忽略所有字符到下一个换行符。如果你想确保它们的空间,在(内)循环添加一个测试 - 但你必须决定做什么如果字符不是空格

That code simply ignores all characters up to the next newline. If you want to ensure that they are spaces, add a test in the (inner) loop - but you have to decide what to do if the character is not a space.

这篇关于使用与fgets时忽略多余的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆