编辑:我不得不添加一个 getchar(); scanf("%i", &choice); 现在它只问一次!
显然它是导致它输出两次的 case 开关。如果我在 case 开关之外调用该函数,它会输出 1,但如果我在开关内部调用它,它会输出两次
这是什么原因造成的?我怀疑scanf的选择?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void test();
void choose();
int main(void)
{
//if i call here its fine
test();
choose();
return 0;
}
void choose()
{
int choice;
do
{
printf("1 - Testing if double ask\n");
printf("2 - Exit\n");
printf("Please enter your choice: ");
scanf("%i", &choice);
switch(choice)
{//but pressing 1 here asks twice?
case 1:
test();
break;
default:
if(choice !=2)
printf("Input Not Recognized!\n");
break;
}
}
while(choice !=2);
if(choice == 2)
printf("Ciao!");
}
void test()
{
printf("HELLO");
char *name = malloc (256);
do
{
printf("Would you like to continue (y/n)\n");
fgets(name, 256, stdin);
}
while(strncmp(name, "n", 1) != 0);
free (name);
}