gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:04:43 24 4
gpt4 key购买 nike

输入无效字符时,我会双重读取输入内容。这将导致重复两次初始菜单!确实发送了帮助,但我不确定是什么问题。我觉得这是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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com