我有以下代码:
#include <stdio.h>
#include <stdlib.h>
int main (){
int s1 = 0;
int s2 = 0;
int frstEscolha;
do{
printf("\n\n WELCOME \n\n");
printf(" 1- JOGAR \n");
printf(" 2- SAIR \n");
scanf ("%d", &frstEscolha);
printf ("%d %d",s1,s2);
switch (frstEscolha) {
system ("cls");
int sndEscolha;
case (1):
s1 = 1;
printf ("\n\n NUMBER OF PLAYERS \n\n");
printf ("1- ONE PLAYER \n");
printf ("2- TWO PLAYERS \n");
scanf ("%d", & sndEscolha);
system ("cls");
do{
switch (sndEscolha) {
char *trdENome , *trdENome1, *trdENome2;
case (1):
s2 = 1;
printf ("\nPLAYER NAME: \n");
scanf ("%s", &trdENome);
printf("\nGOOD GAME %s \n\n", &trdENome);
case (2):
s2 = 1;
printf ("\nPLAYER 1 NAME \n");
scanf ("%s", &trdENome1);
printf ("\nPLAYER 2 NAME \n");
scanf ("%s", &trdENome2);
printf("\nGOOD GAME %s e %s \n\n", &trdENome1, &trdENome2);
default :
printf ("Invalid character, try again!!");
s2 = 0;
}
}
while (s2==0);
case (2): exit (0);
default :
printf ("Invalid character, try again!!");
s1 = 0;
}
}
while (s1 == 0);
return 0;
}
这应该打印一个菜单,让你选择导航不同菜单的选项,while用于在插入的字符无效时重复该过程,但是当发生这种情况时控制台开始闪烁并且程序崩溃。这是怎么造成的,我该如何解决? 感谢
答案 0 :(得分:-2)
运行代码后,似乎无法控制地闪烁,程序运行得非常好。什么都没有崩溃或错误。代码中唯一的问题是switch
语句。他们最终陷入无限循环。我建议的是在每个案例的末尾添加break;
以摆脱该循环。除此之外,您的代码似乎运行良好。
以下代码仅用于修复
中的无限循环问题switch
语句
case(1):
//your code here
break;
我相信我发现了您的代码错误。在您关于您的问题的简要描述中,我碰巧发现了错误。在您scanf
中,如果用户输入了一个字符,程序就会中断。 我的编译器不断重复这个问题。
我建议使用if/else
循环来解决您的问题。另一种解决方案是将int frstEscolha
更改为unsigned int frstEscolha
。如果用户碰巧输入了一个字符,那么它可以在不破坏程序的情况下获得字符的值。但强烈建议在这种情况下使用if/else
。
如果您使用unsigned int
,则scan
的工作方式如下。
scanf("%lf", &varName);