Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf("%c") call seems to be skipped

Tags:

c

scanf

I tried this code below, but it seems scanf("%c") is skipped. It only asks me to enter name and age and skips the lines below that. It just print the text in the printf above the if statements. Can anyone help?

#include<stdio.h>

int main()
{
    int age;
    char sex;
    char name[20];
    char status;
    printf("Enter your last name\n");
    scanf("%s", &name);

    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);
}
like image 500
Dezhou Zhang Avatar asked Apr 21 '15 14:04

Dezhou Zhang


People also ask

Why is my scanf skipped?

Since it is of %d type specifier, when you press Enter A newline character ( '\n' ) is left in the stream and the next scanf() tries to read that newline character, and thus, it seems as though it just skipped input, but in fact, it read the newline character.

Why is scanf not waiting for input?

If we enter the values separated by space, the function returns when space is encountered but the values after space remains in the input buffer. That's why the second scanf() function will not wait for user input, instead it takes the input from the buffer.

Why does scanf skip one input every time the loop runs?

That means the next time you read from standard input there will be a newline waiting for you (which will make the next scanf() call return instantly with no data). To avoid this, you can modify your code to something like: scanf("%c%*c", &currentGuess);


1 Answers

Change

scanf("%c", &sex);

to

scanf(" %c", &sex);
       ^
      space

and

scanf("%c", &status);

to

scanf(" %c", &status);
       ^
      space

The problem is because of trailing newline characters after your second call to scanf(). Since it is of %d type specifier, when you press Enter A newline character ( '\n' ) is left in the stream and the next scanf() tries to read that newline character, and thus, it seems as though it just skipped input, but in fact, it read the newline character.

So, the newline character is stored in the variable sex, and thus, it skips asking you for input for that variable.

like image 153
Arun A S Avatar answered Nov 09 '22 00:11

Arun A S