input - Read two characters consecutively using scanf() in C -


i trying input 2 characters user t number of times. here code :

int main() {     int t;     scanf("%d",&t);     char a,b;      for(i=0; i<t; i++)     {         printf("enter a: ");         scanf("%c",&a);          printf("enter b:");         scanf("%c",&b);     }     return 0; } 

strangely output first time is:

enter a:  enter b: 

that is, code doesn't wait value of a.

the problem scanf("%d", &t) leaves newline in input buffer, consumed scanf("%c", &a) (and hence a assigned newline character). have consume newline getchar();.

another approach add space in scanf() format specifier ignore leading whitespace characters (this includes newline). example:

for(i=0; i<t; i++) {     printf("enter a: ");     scanf(" %c",&a);      printf("enter b: ");     scanf(" %c",&b); } 

if prefer using getchar() consume newlines, you'd have this:

for(i=0; i<t; i++) {     getchar();     printf("enter a: ");     scanf("%c",&a);      getchar();     printf("enter b:");     scanf("%c",&b);  } 

i consider former approach superior, because ignores arbitrary number of whitespaces, whereas getchar() consumes one.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -