【问题标题】:how to read a line from stdin again after reading something from stdin in C? [duplicate]从 C 中的标准输入读取内容后,如何再次从标准输入读取一行? [复制]
【发布时间】:2020-03-07 22:15:42
【问题描述】:

这个程序运行良好。

int main()
{
    {
        printf("Type something:\n");
        char* message = malloc(64 * sizeof(char));
        fgets(message, 64, stdin);
        printf("message ist : %s\n", message);
        free(message);
    }
}

但是当我运行以下程序时,它不允许我写任何东西,它打印“message ist:”

int main()
{
    char action;

    while(action!='e')
    {
        printf("print a line: p\n");
        printf("End Program:  e\n");

        action = getc(stdin);

        if(action == 'p')
        {
            fflush(stdin);
            printf("Type something:\n");
            char* message = malloc(64 * sizeof(char));
            fgets(message, 64, stdin);
            printf("message ist : %s\n", message);
            free(message);
        }
        else if(action == 'e')
        {
            printf(" Program ended successfully\n");
            exit(0);
        }
    }
}

有没有人解释为什么它让我在第一个程序中输入, 为什么它不让我在第二个程序中输入?

我尝试刷新键盘输入,但没有成功。 我尝试使用getline() 而不是fgets(),结果相同。

如果有任何想法和解释,我将不胜感激。

【问题讨论】:

  • 现在是时候开始调试了。调查过action的值吗?而且,顺便说一句,fflush(stdin) 是未定义的行为。
  • 当您输入“p”时,您实际上输入了“p”。 “”是fgets() 看到的唯一字符。
  • 您可能想要初始化 action 而不是将其与未知值进行比较:char action = 0;
  • @klutt: fflush(stdin); 在没有扩展的实现上确实是 UB。例如,Windows 库通过(可能除其他外)定义fflush(stdin); 来扩展C。不过我从不使用它,而且我认为不必要地依赖扩展是不好的。
  • @pmg 如果他们知道他们正在使用扩展,那么他们可以忽略这些建议。如果他们做得不好,那么告诉他们是件好事。 :)

标签: c stdin readline fgets


【解决方案1】:
#include <stdio.h>

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

int main()
{
    char action;
    char message[64] = { };

    while(action != 'e')
    {
        printf("---------\nCommands:\n'p' for print a line\n'e' for end program\n\nType a command: ");
        action = getc(stdin);
        // Exclude unnecessary chars (<Enter> and so on)
        customFlush(); // or fseek(stdin, 0, SEEK_END);

        if (action == 'p')
        {
            memset(message, 0, sizeof(message));
            printf("\nType something:\t");
            fgets(message, 64, stdin);
            printf("\nTyped message:\t%s\n", message);
            // Here is also possible place for calling customFlush or fseek()
        }
    }
    printf("Program ended successfully\n");
}

【讨论】:

    【解决方案2】:

    似乎fflush(stdin)(如前所述未定义)无法正常工作。问题是 '\n' 仍在缓冲区中,必须删除。否则调用fgets,在缓冲区中找到'\n'(这标志着输入的结束)并继续执行程序。

    试试这个:

        // fflush(stdin);
        while (getchar() != '\n');
        printf("Type something:\n");
        char* message = (char*) malloc(64 * sizeof(char));
        fgets(message, 64, stdin);
        printf("message is : %s\n", message);
        free(message);
    

    类似“p MyMessage”的输入也可以正常工作(但可能是无意的)。这确实打印了消息。

    【讨论】:

      猜你喜欢
      • 2020-02-25
      • 1970-01-01
      • 2012-04-25
      • 2013-03-30
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多