【问题标题】:Why doesn't getchar stop to get input?为什么 getchar 不停止获取输入?
【发布时间】:2020-07-30 18:21:18
【问题描述】:

我有以下一段代码,它应该与用户就他想要做什么进行交互。

int input;
printf("Would you like to update the name of the student?\n");
printf("Enter Y(yes) or N(no)\n");
input = getchar();

if (input == 'Y' || input == 'y') {
  printf("Please enter the updated name\n");
  scanf("%s", tmpSt->name);
}

printf("Would you like to update the student's ID?\n");
printf("Enter Y(yes) or N(no)\n");
input = getchar();

但在执行时它不会停止获取第一个输入。

Would you like to update the name of the student?
Enter Y(yes) or N(no)
Would you like to update the student's ID?
Enter Y(yes) or N(no)

它应该得到名称的答案,但它直接进入 id。

【问题讨论】:

  • 我怀疑输入缓冲区中可能有一些东西(可能是前一个输入的尾随换行符),getchar 拾取。尝试打印input,看看值是多少。
  • 我打印了input,它打印了一个换行符

标签: c input scanf user-input getchar


【解决方案1】:

scanf("%s", ...) 将用户输入的换行符留在输入流中等待处理。

使用char c; scanf(" %c", &c); 代替getchar() 初始空格将使scanf() 忽略待处理的空格,包括待处理的换行符。

同时检查scanf()的返回值来检测无效输入和文件结尾。

【讨论】:

  • 我已经用 scanf 试过了,但它做同样的事情:(
  • @SpyrosMouchlianitis:确保" %c" 格式字符串的开头有空格。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多