【问题标题】:Program does not wait before output [duplicate]程序在输出前不等待[重复]
【发布时间】:2014-04-18 18:25:23
【问题描述】:

我是 C 编程的新手,但在使用以下代码时遇到了问题。

#include <stdio.h>

int main(void)

{   
int input_number;
int largest_number = 0; 
char reply; 

printf("Hello world\n");
printf("This is a simple program, that will output the largest number entered\n");
printf("Please enter a number");
while (reply != 'N') 
{  // Start of WHILE loop


printf("Please enter a number");
scanf("%d",&input_number);
if (input_number > largest_number)
    largest_number = input_number;
printf("\nDo you wish to enter another number? Y/N\n");
scanf("%c",&reply); // Problem with this line

}  // End of WHILE loop






printf("%d",largest_number); 
getch();

问题是这样的:当用户输入一个数字时,程序会输出'Do you want to enter another number?是/否'。该程序不会等待答案,而是输出“请输入一个数字”。如果您输入“N”而不是数字,则循环会停止。

如何让程序在输出“请输入一个数字”之前等待,如果回复“您要输入另一个数字吗?”则退出循环是'N'吗?

【问题讨论】:

  • 重复...见我的very detailed answer
  • 注意:您不会将变量 reply 初始化为任何特定值。这意味着在while 循环开始之前,reply 可能 持有'N' 并且您永远不会看到循环执行。

标签: c printf output scanf


【解决方案1】:

第一个scanf 留在缓冲区中的换行符\n 被第二个scanf 读取。你需要消耗它。试试这个

scanf(" %c",&reply);  
       ^ a space before %c can consume any number of white-spaces

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    相关资源
    最近更新 更多