1

编辑:我不得不添加一个 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);
        }
4

2 回答 2

4

第一:您不能将 C 字符串与比较运算符!===. 你需要使用strcmp这个。

Furthermore I think you'll find a do { ... } while loop more useful in this case. You're checking name once before the user has had a chance to add any input.

The next thing to be aware of is that fgets will retain the newline in your input, so you'll need to address this in your usage of strcmp.

于 2012-08-23T01:45:03.270 回答
1

字符串比较在 C 中不像那样工作,您必须在 string.h 中使用 strcmp。

或者,您可以只查看名称中的第一个字符。

while(name[0] != 'n')
于 2012-08-23T01:43:59.857 回答