c - 我的do-while循环有问题,但不确定是什么问题(C语言)

标签 c arrays printf do-while

输入无效字符时,我会双重读取输入内容。这将导致重复两次初始菜单!确实发送了帮助,但我不确定是什么问题。我觉得这是do-while循环的问题,因为如果在菜单中输入了无效字符,它将多次重复菜单。

main.c文件

#include <stdio.h>
#include <stdlib.h>

extern menu();
extern q1();
extern q2();
extern q3();
extern q4();
extern int file[3][6];

void main(void)
{
char option;
do
{
menu();
printf("Enter an option: ");
scanf(" %c", &option);

switch (option)
{
case '1':
printf("Selected 1! \n");
q1();

break;

case '2':
printf("Selected 2! \n");
q2();

break;

case '3':
printf("Selected 3! \n");
q3();

break;

case '4':
printf("Selected 4! \n");
q4();

break;

case 'Q': case 'q':
option = 'Q';

break;

}
} while (option != 'Q');
default:

printf("Error! Please re-enter a valid option. \n\n");

break;
return 0;
}



void menu(void)
{
printf("------------------------------------------------------------------------------------------------------------------------------\n");
printf("1. Display the total number of subscriptions for the selected broadband type \n");
printf("2. Display bimonthly average subscription of the selected broadband type \n");
printf("3. Display top three subscription and their corresponding months of the selected broadband type \n");
printf("4. Find the ratio of the Fibre Based and the Cable Modern subscription in the whole number from Jan to Jun. Display the highest ratio and its corresponding month \n");
printf("Q. Quit the program \n");
printf("-------------------------------------------------------------------------------------------------------------------------------\n\n");
}


void q1(void)
{
int type1, a, total1 = 0;

printf("1. DSL \n");
printf("2. Cable Mordem \n");
printf("3. Fibre Based \n");

printf("Please select broadband time (1 - DSL): ");
scanf(" %d", &type1);

if (type1 < 4)
{
for (a = 0; a < 5; a++)
{

total1 = total1 + file[type1 - 1][a];

}


printf("The total number of subscription is %d \n", total1);

}
else
{
    printf("Error! Please enter a valid option \n");
}
}

最佳答案

scanf("%c", &option);是一个问题。 %c后面的空间并不总是有效。

使用类似:

scanf("%c", &option);
getchar();


要么

scanf("%c %*c", &option);


捕捉换行符\n字符。

您还将default:放在完全不在switch之外的陌生地方。



default: break;


在交换机内部。

关于c - 我的do-while循环有问题,但不确定是什么问题(C语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60061233/

相关文章:

c - 隐式和显式转换

python - 从生成器创建两个串联数组

c - 多次调用 char[] 立即返回函数 fprint

c - 作用域会影响函数调用的前后增量吗?

c++ - 等号是否在 char * 中重新分配内存?

c - 我怎样才能再次这样做?在C中

JavaScript:方便使用 3 维数组吗?

c - 格式参数过多(printf 函数)

c - 解释 printf 中的求值顺序

c - glib:valgrind 在 g_strsplit 之后报告 'still reachable' block