【问题标题】:Program skips parts of code程序跳过部分代码
【发布时间】:2014-03-22 10:51:26
【问题描述】:

我的 c 代码一直有一个问题,每当我收到输入并调用函数时,它都会跳过函数的第一部分并执行下一部分。

编辑:问题已解决,此代码运行正常。

使用 while((c= getchar()) != '\n' && c != EOF);毕竟输入

void Fruit(void); 
void Fruit2(void);
void Chocolate(void);

int choice=0;
char fruit[32];
char fruit2[32];
char Choco[32];
int c;
int main()
{
printf("Which food do you prefer, 1=Fruit?, 2=Chocolate?");
scanf("%d",&choice);
while((c = getchar()) != '\n' && c != EOF);

                if(choice==1)
                {
                Fruit();
                }
                        else if(choice==2)
                        {
                        Chocolate();
                        }
                                    else
                                    {
                                    printf("Pick one");
                                    }
}


void Fruit(void)
{
     printf("Enter your favourite fruit?\n");
     gets(fruit);
     while((c= getchar()) != '\n' && c != EOF);
     printf("What is your second most favourite fruit?\n\n");
     gets(fruit2);
     while((c = getchar()) != '\n' && c != EOF);
     system("cls");
     printf("You like %s's and %s's ",fruit,fruit2);
     getch();
}

void Chocolate(void)
{
     printf("Enter your favourite chocolate bar\n\n");
     gets(Choco);
     while((c = getchar()) != '\n' && c != EOF);
     system("cls");
     printf("You like %s",Choco);  
     getch();   
}

【问题讨论】:

  • 这是一个很大的常见问题解答。提示:选择一个值开始后谁会使用换行符?
  • 你在选择2后点击ENTER了吗?
  • 我会先尝试修复“printf("You like %s");”。你想在这里打印什么?

标签: c string file function


【解决方案1】:

代替

    printf("You like %s's and %s's ");

你应该有

     printf("You like %s's and %s's ", fruit, fruit2);

第二个打印语句也是如此。

【讨论】:

  • 并且gets()也不应该被使用。
【解决方案2】:

函数Chocolate() 中的函数gets 读取scanf 留下的\n 字符。在按下 Enter 键时,带有输入的额外字符 \n 将传递到缓冲区。 scanf 不读取此字符。您需要在调用gets 之前使用它。

可能的解决方案: What can I use to flush input?


我建议你不要使用gets。它现在已从 C 标准中删除。相反,您可以使用fgets

fgets(fruit, sizeof(fruit), stdin);  

【讨论】:

  • 我确信您还没有阅读我的回答中提供的链接。
  • 答案已经解释过了。我无法解释得比这更好。简单来说,while((c = getchar()) != '\n' && c != EOF); 将消耗您的 \n(以及输入缓冲区中的所有其他字符)。
  • 我把这个放在哪里?在任何 \n 之后?
  • 把这个放在你的scanfgets之后。
  • 我猜 c 只是一个计数器变量
猜你喜欢
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多