Scanf asks for two values instead of one
When I compile this code, it causes scanf to ask for the value twice when I select selection A. What am I missing here?
This is not the first time this has been encountered, so I suspect I cannot figure out something pretty 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;
}
source to share
scanf("%d\n", &a);
it should be scanf("%d", &a);
Also read the Related question .
In the first case, after reading an integer and saving to a string, the argument is scanf
not exhausted. Looking at it \n
, scanf will consume all whitespace (newline, tabs, markup, etc.) that it sees (and remains locked) until it encounters a non-whitespace character. On encountering a character with no spaces scanf
will return.
Tutorial: Don't use space, newline, etc. as the end character in scanf. If a whitespace character is at the beginning of an argument string, scanf can still skip any number of whitespace characters , including zero . But when the whitespace characters are trailing characters, it will also use your new line character, unless you type a character without spaces and hit the return key.
source to share
// the trailing '\n' in the scanf format string
// is what is causing the dual inputs
// the returned value from I/O statements (I.E. scanf)
// needs to be checked to assure operation was successful
#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");
// note
// leading ' ' in format string to consume leading white space
// and no trailing '\n'
if( 1 != scanf(" %c", &choice) )
{ // then, scanf failed
// handle error condition
perror("scanf failed for choice");
exit(EXIT_FAILURE);
}
// implied else, scanf successful
switch (choice)
{
case 'A':
{ // braces needed due to variable declaration
int a = 0; // corrected ':' to ';'
printf("you've chosen menu A\n");
printf("enter a number\n");
// note
// leading ' ' in format string to consume leading white space
// and no trailing '\n'
if( 1 != scanf(" %d", &a) )
{ // then scanf failed
// handle error condition
perror("scanf failed for number");
exit(EXIT_FAILURE);
}
// implied else, scanf successful
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;
} // end switch
return 0;
} // end function: main
source to share