【问题标题】:Why does the use of fgets result in an infinite loop when Ctrl-d is pressed?为什么按下 Ctrl-d 时使用 fgets 会导致无限循环?
【发布时间】:2021-12-05 13:06:28
【问题描述】:

下面的程序提示用户输入一些东西。如果fgets 可以接受输入,程序将打印用户输入的内容。该程序可以工作,只是当用户在提示符下按下 Ctrld 时会发生一些奇怪的事情。当用户在提示符处按下 Ctrld 时,程序会进入一个无限循环,提示符会一遍又一遍地打印出来。为什么会这样?

#include <stdio.h>
#define BUFSIZE 512

int main(void)
{
    char input_buf[BUFSIZE];
    char *user_input;
    while (1) {
        user_input = NULL;
        printf("Input: ");  /* Prompt. */
        if ((user_input = fgets(input_buf, BUFSIZE, stdin)) == NULL) {
            printf("Invalid input. Try again.\n");
            continue;
        } else {
            printf("User input: %s", user_input);
            break;
        }
    }
    return 0;
}

【问题讨论】:

  • stdin 关闭时,也许continue 不是最佳选择?
  • while(1) 是一个无限循环,如果你从不打破它
  • 一旦用户输入Control-Dfgets将永远返回NULL。然后你的程序将continue。直到1 更改为另一件事,这将需要,嗯,永远......
  • @arfneto 为什么fgets 会在用户按下Ctrl-d 后永远返回NULL
  • 在某些平台上关闭 stdin ... control-z

标签: c fgets


【解决方案1】:

如果您想在文件明显结束后继续阅读(或尝试),请在 continue; 之前插入 clearerr(stdin);

在具有默认终端设置的 Unix 系统中按 Control-D 会将用户当前键入的任何内容发送到进程。如果用户没有输入任何新内容(当 Control-D 在一行的开头或紧接着另一个 Control-D 之后按下时会发生这种情况),该进程将收到零字符,C 流软件将此视为软文件结束指示。

然后在流上的进一步 I/O 尝试报告文件结尾,直到您清除“错误”。

(关于 Control-D 作用的更多信息是here。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    相关资源
    最近更新 更多