c - scanf asking for two values instead of one -
this question has answer here:
- scanf() curious behaviour! 3 answers
when compile code, leads scanf asking value twice when pick choice a. missing here?
this isn't first time encountered, i'm suspecting i'm failing grasp rather fundamental scanf.
#include <stdio.h> #include <stdlib.h> int main() { char choice; printf("1. 'enter 'a' choice\n"); printf("2. 'enter 'b' choice\n"); printf("3. 'enter 'c' choice\n"); scanf("%c", &choice); switch (choice) { case 'a': { int =0; printf("you've chosen menu a\n"); printf("enter 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 invalid\n!"); break; } return 0; }
scanf("%d\n", &a);
should scanf("%d", &a);
also read related question.
in former case after reading integer , storing a, scanf
's argument string not exhausted. looking @ \n
, scanf consume whitespaces (newline, tab, spaced etc) sees (and remain blocked) until encounters non-whitespace character. on encountering non-whitespace character scanf
return.
learning: don't use space, newline etc trailing character in scanf. if space character in beginning of argument string, scanf may still skip number of white space characters including zero characters. when whitespace trailing characters, eat new line character unless type non-whitespace character , hit return key.
Comments
Post a Comment