编辑:我必须添加一个 getchar();在 scanf("%i", &choice) 之后;现在它只询问一次!
显然是大小写开关导致它输出两次。如果我在 case switch 外部调用该函数,它会输出 1,但如果我在 switch 内部调用它,它会输出两次
这是什么原因造成的?我怀疑 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);
}
最佳答案
首先:您不能使用比较运算符 !=
和 ==
来比较 C 字符串。您需要使用 strcmp
为此。
此外,我认为您会发现 do { ... } while
循环在这种情况下更有用。在用户有机会添加任何输入之前,您检查了一次 name
。
接下来要注意的是 fgets
将在您的输入中保留换行符,因此您需要在使用 strcmp
时解决这个问题。
关于c - 获取我的输入并在 while 循环中比较它,fgets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12083648/