【发布时间】:2020-09-26 18:52:42
【问题描述】:
我需要循环 switch 语句直到输入 1 或 2。任何帮助都会很好或示例代码。我尝试使用 while 循环,但它一直在崩溃。我也尝试了一个do while,它变成了一个无限循环,所以我一定是做错了什么。
int main (void)
{
int choice; // choice to run program from start menu or quit
while (1)
{
// Menu for entering resistor and capacitor values
printf("Welcome to the 555 Timer Frequency and Duty Cycle Calculator\n");
printf("Please enter two resistor values in between ");
printf("1 kOhms and 100 kOhms and a capacitor value\n\n");
//Start of menu
printf("Menu\n\n");
printf("1. Continue\n");
printf("2. Exit\n");
scanf("%d", &choice); // User inputs value
switch (choice)
{
case 1:
resistor(); // Program resistor is run if 1 is input
break;
case 2:
printf("Goodbye."); // Program ends if 2 is input
break; // break is used to exit while loop
default:
printf("Sorry I do not understand\n\n");
fflush(stdin); /* clears input buffer to allow user to input a new value if anything other
than 1 or 2 is input into scanf */
}
break;
}
return 0;
}
【问题讨论】:
-
fflush(stdin);为什么?您只需要刷新输出缓冲区 -
我该怎么做?
-
通过
stdout而不是标准输入。但我没有看到崩溃godbolt.org/z/cnfv5W -
我需要刷新我认为是标准输入的用户输入的选择?此外,每当输入除 1 或 2 以外的整数或字符时,它都会变成无限循环,我需要它来打印语句“对不起,我不明白”,然后重新运行菜单
-
fflush(stdin)是未定义的行为,应该避免。
标签: c