代码与gets()和printf无法正常工作

时间:2015-06-06 04:42:16

标签: get printf gets

所以,我试图做这个代码,说'"你好先生"或"你好太太"取决于用户的性别,但是当我运行程序时,它不会让我输入我的名字,但为什么?

另外,我尝试使用fgets(),但编译器说" 关于功能' fgets' "

#include <string.h>
#include <math.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void flushstdin()
{
    int c;
    while((c=getchar())!= '\n' && c != EOF);
}

int main () {
    float sex;
    char name[60];
    printf("\nInform your sex: 1 if you are male, 2 if you are female.");
        while(scanf("%f",&sex)!=1 || sex!=1 && sex!=2){ //In case the person typed something different of 1,2.
            printf("\nInform a correct value, 1 or 2.\n");
            flushstdin();
        }if(sex==1){
                printf("Inform your name.\n");
                gets(name);
                printf("\nHello Mr. %s \n",name);
            }
        if(sex==2){
                printf("Inform your name.\n");
                gets(name);
                printf("\nHello Mrs. %s \n",name);
       }
    system("pause");
    return 1;
    }

1 个答案:

答案 0 :(得分:2)

在这种情况下,当按Enter键传递用户是女性还是男性的数据时,输入的字符是&#39; \ n&#39;仍在输入缓冲区中的队列中。使用scanf时会发生这种情况。这意味着后面的gets()函数将读取&#39; \ n&#39;仍然在缓冲区中而没有先询问用户的字符。

一个简单的解决方案是在询问用户将收到缓冲区中剩余输入的性别后添加两行代码:

    #include <string.h>
    #include <math.h>
    #include <ctype.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>

    void flushstdin() {
        int c;
        while((c=getchar())!= '\n' && c != EOF);
    }

   int main () {
        float sex;
        char name[60];
        printf("\nInform your sex: 1 if you are male, 2 if you are female.");
        while(scanf("%f",&sex)!=1 || sex!=1 && sex!=2){ //In case the person typed something different of 1,2.
            printf("\nInform a correct value, 1 or 2.\n");
            flushstdin();
        }

        //new code, extracts input from buffer until it reads a '\n' character or buffer is empty

        char c;
        while(( c = getchar()) != '\n' && c != EOF);

        //end of new code

        if(sex==1){
            printf("Inform your name.\n");
            gets(name);
            printf("\nHello Mr. %s \n",name);
        }
        if(sex==2){
            printf("Inform your name.\n");
            gets(name);
            printf("\nHello Mrs. %s \n",name);
        }

        system("pause");
        return 1;
    }