Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf asking for two values instead of one [duplicate]

Tags:

c

scanf

When I compile this code, it leads to scanf asking for a value twice when I pick choice A. What am I missing here?

This isn't the first time this is encountered, so I'm suspecting I'm failing to grasp something rather fundamental with scanf.

#include <stdio.h>
#include <stdlib.h>

int main()
{

char choice;
printf("1. 'enter 'A' for this choice\n");
printf("2. 'enter 'B' for this choice\n");
printf("3. 'enter 'C' for this choice\n");

scanf("%c", &choice);

switch (choice)
{
case 'A':
    {
        int a =0;
        printf("you've chosen menu A\n");
        printf("enter a number\n");
        scanf("%d\n", &a);
        printf("%d\n", a);
    }
break;
case 'B':
printf("you've chosen B\n");
break;
case 'C':
printf("you've chosen C\n");
break;
default:
printf("your choice is invalid\n!");
break;
}

return 0;

}
like image 751
andresimo Avatar asked Dec 25 '22 01:12

andresimo


2 Answers

scanf("%d\n", &a); should be scanf("%d", &a);

Also read Related question.

In former case after reading an integer and storing into a, scanf's argument string is not exhausted. Looking at \n, scanf would consume all the whitespaces (newline, tab, spaced etc) it sees (And will remain blocked) until it encounters a non-whitespace character. On encountering a non-whitespace character scanf would return.

Learning: Don't use space, newline etc as trailing character in scanf. If the space character is in the beginning of argument string, scanf may still skip any number of white space characters including zero characters. But when whitespace is a trailing characters, it would eat your new line character also unless you type a non-whitespace character and hit return key.

like image 170
Mohit Jain Avatar answered Dec 29 '22 00:12

Mohit Jain


Simply remove the newline character from scanf("%d\n", &a); and it will not ask to enter a value twice

like image 39
Raghvendra Kumar Avatar answered Dec 28 '22 22:12

Raghvendra Kumar