skipping of some scanf in between

2019-09-07 16:34发布

问题:

In this program the second and forth scanf get skipping , don't know the reason . can some please tell the reason ?

#include<stdio.h>
main()
{
 int age;
  char sex,status,city;
   printf("Enter the persons age \n");
   scanf("\n%d",&age);
   printf("enter the gender\n");
   scanf("%c",&sex);
   printf("enter the health status");
   scanf("%c",&status);
   printf("where the person stay city or village");
   scanf("%c",&city);
   if(((age>25)&&(age<35))&&(sex=='m')&&(status=='g')&&(city=='c'))
   printf("42");
   else if(age>25&&age<35&&sex=='f'&&status=='g'&&city=='c')
    printf("31");
    else if(age>25&&age<35&&sex=='m'&&status=='b'&&city=='v')
   printf("60");
  else
  printf("no");

       }

回答1:

When reading chars using scanf(), it leaves a newline char in the input buffer.

Change :

   scanf("%c",&sex);
   printf("enter the health status");
   scanf("%c",&status);
   printf("where the person stay city or village");
   scanf("%c",&city);

to:

   scanf(" %c",&sex);
   printf("enter the health status");
   scanf(" %c",&status);
   printf("where the person stay city or village");
   scanf(" %c",&city);

Notice the leading whitespace in scanf's format string which tells scanf to ignore whitespaces.

Alternatively, you can use getchar() for consuming the newline chars.

   scanf("%c",&sex);
   getchar();
   printf("enter the health status");
   scanf("%c",&status);
   getchar();
   printf("where the person stay city or village");
   scanf("%c",&city);
   getchar();


回答2:

I always get the same problem as you using scanf, therefore, I use strings instead. I would use:

#include<stdio.h>
main()
{
    int age;
    char sex[3],status[3],city[3];
    printf("Enter the persons age \n");
    scanf("\n%d",&age);
    printf("enter the gender\n");
    gets(sex);
    printf("enter the health status");
    gets(status);
    printf("where the person stay city or village");
    gets(city);
    if(((age>25)&&(age<35))&&(sex[0]=='m')&&(status[0]=='g')&&(city[0]=='c'))
        printf("42");
    else if(age>25&&age<35&&sex[0]=='f'&&status[0]=='g'&&city[0]=='c')
        printf("31");
    else if(age>25&&age<35&&sex[0]=='m'&&status[0]=='b'&&city[0]=='v')
        printf("60");
    else
        printf("no");
}

If the first scanf is still giving you problems (skipping the second question, gets), you can use a little trick, but you have to include a new library

#include<stdlib.h>
...
char age[4];
...
gets(age);
...
if(((atoi(age)>25)&&(atoi(age)<35))&&(sex[0]=='m')&&(status[0]=='g')&&(city[0]=='c'))

And use atoi every time you use age, because atoi converts a char string into an integer (int).



标签: c char scanf