我做了一个switch-case程序,当我给出输入时,它不会执行switch-case
我的目标是当我们给输入n时,它应该执行全局声明的函数。在输入之后,它不会进入switch语句。Place我做了一个switch-case程序,当我给出输入时,它不会执行switch-case,c,switch-statement,C,Switch Statement,我的目标是当我们给输入n时,它应该执行全局声明的函数。在输入之后,它不会进入switch语句。Place void booking() { //globally declared function printf("please select the seats"); printf("1A 2A 3A G"); } int main() { //Main function int n; clrscr();
void booking() { //globally declared function
printf("please select the seats");
printf("1A 2A 3A G");
}
int main() { //Main function
int n;
clrscr();
printf("\t\t\t Railway reservation system");
printf("1.Booking");
printf("2.Availability checking");
printf("3.Cancellation");
printf("4.Prpare chart");
scanf("%d",&n);
switch(n) //when I give input as 1 switch case is not being executed
{
case 1:
booking(); //after the input it should execute this global function.
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
return n;
}
在
返回
语句之前,您将在控制台屏幕关闭之前看到它。事实上,switch case已执行,但您可能无法看到它,因为您的程序很快完成。请尝试从命令行执行它,或在末尾添加类似的内容:
printf("Press any key to exit...");
while (!kbhit()) ;
还有一件事:将新行字符('\n')放在菜单中每一行的末尾。也许问题在于打印时没有刷新输出缓冲区,所以看不到消息?在打印的输出中添加尾随换行符。还要尝试在调试器中单步执行代码。除非您是从控制台窗口运行,否则输出窗口可能关闭得太快,您看不到结果。对我来说“正常”,但缺少换行符使输出非常难以读取。“没有进入switch语句”:您在调试器中验证了吗?相反会发生什么?
kbhit
是非标准的,建议getchar
和消息“按Enter退出…”WeatherVane不要忘记字符串中的尾随换行符,或者调用fflush
@WeatherVane:OP的clrsc
也是如此,他似乎不介意。不是我的DV,尽管我知道为什么。谢谢你的回答,它是有效的……如果我没有错,我们使用switch case语句来避免使用函数,对吗。。。。。不是真的,更多,而不是很长的if/else语句。你也可以把它放在一个函数中,这样就很好了。
do {
printf("Press q to quit: ");
user_in = getchar();
} while (user_in != 'q');