C 有人能在我的程序中解释FGET的行为吗?

C 有人能在我的程序中解释FGET的行为吗?,c,C,当我在下面的代码段中使用fgets而printf中没有换行符时,程序不会等待我的输入。看起来要么在printf语句中使用新行字符,要么使用刷新stdin来解决问题。但是有人能解释发生了什么以及为什么\n或flsuhing会修复它吗 #include <stdio.h> #include <stdlib.h> int main(void) { char *userInput = malloc(sizeof(*userInput) * 2); pri

当我在下面的代码段中使用fgets而printf中没有换行符时,程序不会等待我的输入。看起来要么在printf语句中使用新行字符,要么使用刷新stdin来解决问题。但是有人能解释发生了什么以及为什么\n或flsuhing会修复它吗

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


int main(void)

{

    char *userInput = malloc(sizeof(*userInput) * 2);

    printf("Enter a character:"); // This leads to an issue where fgets does not wait for an input

    /* 
    Using either of the below statements fixes it though 

    printf("Enter a character:\n");

    OR 

    fflush

    */


    fgets(userInput, 2, stdin);

    printf("The character you entered is: %c \n", userInput[0]);

}
#包括
#包括
内部主(空)
{
char*userInput=malloc(sizeof(*userInput)*2);
printf(“输入字符:”;//这会导致fgets不等待输入的问题
/* 
不过,使用以下任一语句都可以修复它
printf(“输入字符:\n”);
或
刷新缓冲区
*/
fgets(用户输入,2,标准输入);
printf(“您输入的字符是:%c\n”,userInput[0]);
}

谢谢

对于我知道的所有C运行时,
stdout
在连接到终端时是行缓冲的(并且在连接到其他任何东西时是块缓冲的),因此只有在输出换行时输出才会刷新到屏幕,或者使用
fflush
显式刷新缓冲区。如果没有换行符(或
fflush(stdout)
调用),
printf
输出将进入缓冲区,但不会刷新到屏幕


显然,
fflush(stdout)
解决了这个问题,实际上输出换行符也是如此。您还可以使用全局禁用stdout的缓冲,尽管这可能会降低I/O速度。

这是让用户输入单个字符然后将该字符回显到终端的正确方法

#include <stdio.h>


int main(void)
{
    int userInput;

    printf("Enter a character:\n");

    if( (userInput = getchar() != EOF) )
    {
        printf("The character you entered is: %c \n", userInput);
    }
}
#包括
内部主(空)
{
int用户输入;
printf(“输入字符:\n”);
if((userInput=getchar()!=EOF))
{
printf(“您输入的字符是:%c\n”,userInput);
}
}

您的注释讨论了用户输入两个字符,但您的代码只查找1个字符(如您对用户的提示所示)

您还可以查看以下内容的可能副本:
char*userInput=malloc(sizeof(*userInput)*2)这将分配(在32位体系结构上)8个字节。然而,当从
stdin
(和类似的源代码)读取时,1024字节左右的大小会更好。建议:
char*userInput=malloc(1024)
并始终检查(!=NULL)返回值以确保操作成功。然后对
fgets()
的调用应该是`if(fgets(userInput,sizeof(userInput),stdin)==NULL){//handle error and exit}@user3629249谢谢您的输入,但是如果我的程序只需要从stdin读取2个字符,分配1024字节还有什么好处吗?如果您想让用户输入2个字符,然后1)要求输入两个字符,2)检查以确保用户输入了两个字符,而不仅仅是单个字符和换行符或换行符。3) 在典型的
fgets()
使用中,输入中将包含一个换行符,用户输入中将追加一个NUL字节。因此,所需的输入大小将为4个字符,即
\n\0
对于4个字符,无需调用
malloc()
fgets(userInput,sizeof(userInput),stdin)请查看您的代码一次并编辑
if((userInput=getchar()!=EOF))
行,因为它将始终打印1或0而不是输入的字符