我尝试使用循环编写C语言程序,该循环重复进行直到从键盘输入特定字符为止。这是我的代码:
#include <stdio.h>
main ()
{
char option;
do
{
printf("Enter q to quit: ");
option = getchar ();
}
while (option != 'q');
}
我也尝试过用scanf(),但是结果总是一样的。这是我尝试测试该程序后的输出:
Enter q to quit: 3
Enter q to quit: Enter q to quit: 2
Enter q to quit: Enter q to quit: 1
Enter q to quit: Enter q to quit: q
谁能向我解释为什么“输入q退出:”总是出现两次,我该如何解决?
之所以将它打印两次,是因为在您按Enter键时,\n
在标准输入后附加了换行符。
您可以通过添加额外的getchar来放弃该换行符:
do
{
printf("Enter q to quit: ");
option = getchar();
getchar(); // discard line feed
}while (option != 'q');
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句