【问题标题】:C - Program exits when input exceeds fgets allowanceC - 当输入超过 fgets 限额时程序退出
【发布时间】:2012-11-23 16:16:29
【问题描述】:

我有以下用 C 编写的程序:

这个程序的主要问题是,如果在使用 fgets() 函数时输入超过 80 个字符,程序就会立即退出。其他代码被执行,但是它不等待用户按下回车。它就像只是忽略了最后的 getchar。

请问我该如何解决这个问题?

【问题讨论】:

  • 您可能还想重新考虑自动删除换行符(除了您提出的问题,下面将轻松回答)。如果输入超过 80 个字符,则缓冲区中没有换行符,并且您正在正式覆盖用户数据。不是严重错误,只是逻辑错误,在这种情况下会丢失密码内容。

标签: c passwords exit fgets


【解决方案1】:

如果用户输入长于fgets 可能从stdin 读取的79 个字符(它最多可以读取比其大小参数说的少一个,因为它以0 终止缓冲区),剩余的输入是留在输入缓冲区中,因此最后的getchar() 立即成功。

为避免这种情况,如果输入太长,您需要清除输入缓冲区。

问题是如果输入足够短,你不知道是否清除缓冲区。所以检查你是否真的得到了fgets 读入的换行符,

int len = strlen(password);
if (password[len-1] == '\n') {
    // got a newline, all input read, overwrite newline
    password[len-1] = 0;
} else {
    // no newline, input too long, clear buffer
    int ch;
    while ((ch = getchar()) != EOF && ch != '\n');
    if (ch == EOF) {
        // input error, stdin closed or corrupted, what now?
    }
}

【讨论】:

    【解决方案2】:

    检查fgets()是否读取了换行符,如果在遇到换行符之前不跳过输入:

    if (0 == strrchr(password, '\n'))
    {
        /* Skip until new-line. */
        int c;
        while (EOF != (c = getchar()) && '\n' != c);
    }
    

    否则对getchar() 的调用将读取fgets() 没有读取的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      相关资源
      最近更新 更多