【发布时间】:2013-12-30 02:24:03
【问题描述】:
虽然这是一个非常简单的问题,但我正在编写一个程序,它陷入了无限的“while”循环,因为中断循环的参数是由需要用户输入的 switch 语句确定的。问题是程序永远不会停止输入,因此它不断选择默认情况,导致无限循环。
这是我目前的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float nickels, dimes, quarters, total, price;
char input;
price = 1.00;
total = 0;
while(total < price){
printf("n = nickel, d = dime, q = quarter: ");
scanf("%c", &input);
switch(input){
case 'n': case 'N':
total += 0.05;
printf("\nTotal: %f\n", total);
break;
case 'd': case 'D':
total += 0.10;
printf("\nTotal: %f\n", total);
break;
case 'q': case 'Q':
total += 0.25;
printf("\nTotal: %f\n", total);
break;
default:
printf("\nWrong input\n");
break;
}
}
printf("You're done! Total is %f", total);
return 0;
}
我知道这是一个非常简单的问题。我为此道歉。这很可能是我忽略的东西。
【问题讨论】:
-
不要
scanf()。 只是不要。fgetc()或fgets()供用户输入。 -
"%c"改为" %c" -
@DennisMeng 一如既往。我们能否请删除
scanf()& co。来自 C14? -
@PhillipKinkade 我知道它不会退出 while 循环,我也不希望它退出。我希望它回到 while 循环的开头并等待用户输入。
-
@Naveed(和 rsheeler):我认为 this 帖子会回答您的问题。
标签: c switch-statement user-input