【问题标题】:Taking my input and comparing it in a while loop, fgets?接受我的输入并在while循环中比较它,fgets?
【发布时间】:2012-08-23 01:40:33
【问题描述】:

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

【问题讨论】:

  • 对那个字符使用单引号或strcmp()(如果它们相等,则为0)。
  • 请在 fgets 后打印出姓名,并将其添加到帖子中。
  • 奇怪,打印出第一个字符怎么样,可能流中有非打印字符?
  • 第一个字符是什么意思? char* 名称?
  • printf("name[0] = '%c'\n", name[0]);

标签: c loops comparison while-loop fgets


【解决方案1】:

首先:您不能使用比较运算符!=== 来比较C 字符串。为此,您需要使用 strcmp

此外,我认为您会发现do { ... } while 循环在这种情况下更有用。在用户有机会添加任何输入之前,您检查了一次name

接下来要注意的是fgets 将在您的输入中保留换行符,因此您需要在使用strcmp 时解决这个问题。

【讨论】:

  • 当你说换行时,你的意思是,当我输入一个字母说“a”时,它会像 printf("a\n") 吗?
  • 啊,好的,那我就不碰它了,因为我需要在文本文件中逐行存储
【解决方案2】:

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

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

while(name[0] != 'n')

【讨论】:

  • 我尝试了 while(name[0]!= 'n' 并且它有效,谢谢,但它仍然问我两次
猜你喜欢
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
  • 2013-01-06
  • 2015-12-15
  • 2011-02-07
  • 1970-01-01
  • 2012-01-07
  • 2017-03-25
相关资源
最近更新 更多