c - fgets 调用之间的空 stdin

标签 c stdin fgets

我有一个代码,我希望 2 个用户输入最多 20 个字符。 我只想保留 20 个。我的问题是,在第一次输入后,如果用户输入超过 20 个字符,这些字符仍然在 stdin 中,因此它将被下一个 fgets 读取。

  char *pseudo = malloc(21);
  fgets(pseudo,21,stdin);
  strtok(pseudo,"\n");

  char * tube = malloc(21);
  fgets(tube,21,stdin);
  strtok(tube,"\n");

我找到了以下在 2 个 fgets 调用之间清空 stdin 的解决方案,它有效,但它在 2 个调用之间阻塞:我必须输入一些内容才能询问第二个输入。

int c = 0;
    while (c != '\n' && c != EOF)
    {
        c = getchar();
    }

最佳答案

您有几个问题:

  • 您的循环逻辑已损坏。
  • 如果您检测到输入行没有以换行符结尾(根本没有执行此操作),则应该只执行固定循环。

像这个简单的例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *pseudo = malloc(21);
    if (fgets(pseudo,21,stdin))
    {
        char *cr = strrchr(pseudo, '\n');
        if (cr == NULL)
        {
            int c;
            while ((c = fgetc(stdin)) != '\n' && c != EOF);
        }
        else
        {
            *cr = 0;
        }
    }
    else
    {
        *pseudo = 0;
    }

    char * tube = malloc(21);
    if (fgets(tube,21,stdin))
    {
        char *cr = strrchr(tube, '\n');
        if (cr == NULL)
        {
            int c;
            while ((c = fgetc(stdin)) != '\n' && c != EOF);
        }
        else
        {
            *cr = 0;
        }
    }
    else
    {
        *tube = 0;
    }

    printf("%s : %s\n", pseudo, tube);

    return 0;
}

输入

01234567890123456789012345
0123456789012345678

输出

01234567890123456789 : 0123456789012345678

显然,您可以重构它,将所有重复的代码放入一个或两个精心设计的函数中,但希望您明白了。

关于c - fgets 调用之间的空 stdin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41602620/

相关文章:

c - sizeof float (3.0) 与 (3.0f)

CreateProcess + CREATE_SUSPENDED 标志在 Linux 中是否等效?

c - read() 用于从标准输入读取流

c - 从字符串中删除元音。

c - 使用 fgets() 从文件复制到字符串的段错误

c++ - 如何编译 Duff 的设备代码?

c - 如何在 SMTP 中的电子邮件中开始新行

linux - 为什么 cat 0>file 不起作用

c - 将 stdin 与 ncurses 一起使用

c - 在 c 中的循环内获取用户输入时,通过将 char * buffer 分配给 '\n' 来清除缓冲区是错误的吗?