在C语言中从stdin中读取内容后,如何再次从stdin中读取一行?

该程序运行正常。

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,stdin);
            printf("message ist : %s\n",message);
            free(message);
        }
        else if(action == 'e')
        {
            printf(" Program ended successfully\n");
            exit(0);
        }
    }
}

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

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

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

ctq1989 回答:在C语言中从stdin中读取内容后,如何再次从stdin中读取一行?

#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,SEEK_END);

        if (action == 'p')
        {
            memset(message,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");
}
,

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

尝试以下方法:

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

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

本文链接:https://www.f2er.com/3118993.html

大家都在问