【发布时间】:2014-03-22 10:51:26
【问题描述】:
我的 c 代码一直有一个问题,每当我收到输入并调用函数时,它都会跳过函数的第一部分并执行下一部分。
编辑:问题已解决,此代码运行正常。
使用 while((c= getchar()) != '\n' && c != EOF);毕竟输入
void Fruit(void);
void Fruit2(void);
void Chocolate(void);
int choice=0;
char fruit[32];
char fruit2[32];
char Choco[32];
int c;
int main()
{
printf("Which food do you prefer, 1=Fruit?, 2=Chocolate?");
scanf("%d",&choice);
while((c = getchar()) != '\n' && c != EOF);
if(choice==1)
{
Fruit();
}
else if(choice==2)
{
Chocolate();
}
else
{
printf("Pick one");
}
}
void Fruit(void)
{
printf("Enter your favourite fruit?\n");
gets(fruit);
while((c= getchar()) != '\n' && c != EOF);
printf("What is your second most favourite fruit?\n\n");
gets(fruit2);
while((c = getchar()) != '\n' && c != EOF);
system("cls");
printf("You like %s's and %s's ",fruit,fruit2);
getch();
}
void Chocolate(void)
{
printf("Enter your favourite chocolate bar\n\n");
gets(Choco);
while((c = getchar()) != '\n' && c != EOF);
system("cls");
printf("You like %s",Choco);
getch();
}
【问题讨论】:
-
这是一个很大的常见问题解答。提示:选择一个值开始后谁会使用换行符?
-
你在选择
2后点击ENTER了吗? -
我会先尝试修复“printf("You like %s");”。你想在这里打印什么?