編輯:我不得不添加一個getchar();在scanf之後(「%i」,&選擇);現在它只要求一次!接受我的輸入並在while循環中比較它,fgets?
顯然它的案例開關導致它輸出兩次。如果我在外殼開關外部調用該功能,它將輸出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);
}
對單個字符或'strcmp()'使用單引號(如果它們相等,則它們將爲'0')。 – alex
請在fgets後打印出姓名,並將其添加到帖子中。 – MWB
@MWB ok,它的發佈 – Dog