与fgets()不等待输入 [英] fgets() not waiting for input

查看:344
本文介绍了与fgets()不等待输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面code:

int N;
scanf("%d", &N);
int i;
for (i = 0; i < N; i++) {
  char line[LINE_MAX];
  if (fgets(line, LINE_MAX, stdin) != NULL) {
    // do stuff with line here
    printf("%c - %c\n", line[0], line[1]);
  }
}

我有具有它具有的行数的输入文件,然后行的该号码接着我想要处理。所以我读的行数为 N 。在那之后,我用与fgets 来得到线能够处理它。

I have an input file which has the number of lines it has, and then that number of lines followed which I want to process. So I read in the number of lines into N. After that, I use fgets to get the line to be able to process it.

然而,与fgets 似乎并没有等待标准输入的第一次。我总是的输出 - ,然后等待输入。这意味着,循环的第一次迭代,它不是在与fgets 等待标准输入和刚打印出由分开的两个空字符 - 我的的printf 一样。

However, fgets does not seem to wait for a stdin the first time. I always get output of -, and then it waits for input. Meaning, the first iteration of the loop, it is not waiting for standard input at fgets and just prints out two empty characters separated by - as my printf does.

这是为什么?我怎样才能获得与fgets 每次等待输入?我觉得这是一个线程问题。

Why is that? How can I get fgets to wait for input each time? I feel like it is a threading issue.

推荐答案

由于 geekosaur 说,你是不是处理新行留下 scanf函数。您可以修改 scanf函数格式字符串,考虑到这一点:

As geekosaur said, you are not handling the newline left behind by scanf. You can modify your scanf format string to take it into account:

scanf("%d *[^\n]", &N);

* [^ \\ n] 说无视你的整数输入后一切不是一个换行符,但不换行(跳过)做任何事

*[^\n] says to ignore everything after your integer input that isn't a newline, but don't do anything with the newline (skip it).

测试程序输出:

emulawsk@cs:~/testing$ ./test2
3
13
1 - 3
26
2 - 6
59
5 - 9

这篇关于与fgets()不等待输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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