C - While 循环复制打印语句

C - While-Loop Duplicating Print Statements

当 while 循环第一次运行时,它会在从标准输入获取用户输入之前打印两次我的 "Create new node" 提示。为什么是这样?查看链接图片。

代码:

int main()
{
  char userInput[2];
  while(1)
  {
    printf("\nCreate new node? (y/n)\n");
    printf(">>> ");
    fgets(userInput, 2, stdin);

    if(strcmp(userInput, "y") == 0)
    {
        printf("Yes\n");
    }

    else if(strcmp(userInput, "n") == 0)
    {
        printf("No\n");
        exit(0);
    }
  }
}

终端输出:

fgets读取字符串加'[=13=]''\n'。由于 userInput 只有 2 字节,'\n' 不会被 fgets 读取,并且会存在于输入缓冲区中。在下一次迭代中,fgets 将读取上一次调用 fgets 留下的 '\n'

增加缓冲区大小就没问题了

char userInput[3];  

或者你可以输入

int ch;
while((ch = getchar()) != '\n' && ch != EOF);

就在 fgets 语句之后。