scanf function seems to be skipped in c

后端 未结 5 468
星月不相逢
星月不相逢 2020-12-06 03:43

I am new to c language, and I tried this code below, but it seems scanf has been skipped, when I run this code, it only asked me enter name and age and skipped the lines bel

5条回答
  •  误落风尘
    2020-12-06 04:30

    Change your code to

    #include
    int  main()
    {
    int age;
    char sex;
    char name[20];
    char status;
    printf("Enter your last name\n");
    // scanf("%s", &name);
    fgets(name,20,stdin);
    
    printf("Enter your age\n");
    scanf("%d", &age);
    
    printf("Enter sex (M/F)\n");
    scanf(" %c", &sex);
    
    
    printf("your status,married, single,irrelevant (M/S/I)\n");
    scanf(" %c", &status);
    if(age>=16 && sex=='M')
    printf("hello, Mr %s\n", name);
    if(age<16 && sex =='M')
    printf("hello, Master %s\n", name);
    if(sex=='F' && status=='M')
    printf("hello, Mrs %s\n", name);
    if(sex=='F' &&(status=='S' ||status=='I'))
    printf("hello,miss %s\n", name);
    return 0;
    }
    

    Here, I have added an extra space before the format specifier %c, to accommodate any previous input like newline (\n).
    Another alternative method is to use getchar() immediately before you take any character input.

    Also, if you perform string input with scanf, it will not read the input after encountering a whitespace. So, instead use fgets for taking any string input which might contain spaces.

    Another thing I changed in your code (trivial) is int main() and return 0.

提交回复
热议问题