c - 获取我的输入并在 while 循环中比较它,fgets?

标签 c loops comparison while-loop fgets

编辑:我必须添加一个 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/

相关文章:

java - 处理与 JavaFx 与 Griffon 的比较

c - 为结构体成员生成随机数

c - 通过c中的函数传递文件

python - 将簇分配给对象中的每个壳 - Maya Python

php - 在 PHP 中用 == 比较不同的字符串返回 true

javascript - 比较多个数组的各个值

c - 针对比使用 libc 构建的更新的 linux 头文件构建

python - 为什么 py2app .app 的启动时间比同一个 python 程序要长?

bash - 在 Bash 中模拟 do-while 循环

loops - AWS 登录循环 - 无法访问门户