简体   繁体   English

程序跳过部分代码

[英]Program skips parts of code

I have been having a constant problem in my c code, whenever I get an input and call a function, it will skip the first part of the function and do the next part.我在我的 c 代码中一直有一个问题,每当我得到一个输入并调用一个函数时,它会跳过函数的第一部分并执行下一部分。

EDIT: Problem has been solved, this code works perfectly normal.编辑:问题已解决,此代码工作正常。

use while((c= getchar()) != '\\n' && c != EOF);使用 while((c= getchar()) != '\\n' && c != EOF); after all input全部输入后

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();   
}

Instead of代替

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

You should have你应该有

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

And similarly for the second print statement.与第二个打印语句类似。

The function gets in your function Chocolate() reads the \\n character left behind by scanf .该函数gets您的函数Chocolate()读取scanf留下的\\n字符。 On pressing Enter key, an extra character \\n with input pass to the buffer.Enter键后,带有输入的额外字符\\n传递到缓冲区。 scanf doesn't read this character. scanf不读取此字符。 You need to consume that before the call of gets .您需要在调用gets之前使用它。

Possible solution: What can I use to flush input?可能的解决方案:我可以用什么来刷新输入?


I would like to suggest you not to use gets .我建议你不要使用gets It is now removed from C standard.它现在已从 C 标准中删除。 Instead you can use fgets .相反,您可以使用fgets

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM