Monday 14 October 2013

Solve problem of scanf() when it take char as input using getchar()

getchar() funtion use to take single character at a time .It is mostly use to remove limitations of scanf() funtion to take character as input.
take a example: 
 #include<stdio.h>  
 main()  
 {  
      char c,ch;  
      printf("\ninsert volue of c :");  
      scanf("%c",&c);  // taking input for c
      printf("\ninsert volue of ch :");  
      scanf("%c",&ch);  //taking input for ch
      printf("\n c =%c && ch = %c",c,ch);  
 }  
Now run it you see that it does not ask for ch to input because it take '\n' (Enter button) as input . we press enter button after inserting volue for c. that enter button goes to ch as input.
so OUTPUT is :-




NOW solve this problem put getchar() after each time use scanf()
 #include<stdio.h>  
 main()  
 {  
      char c,ch;  
      printf("\ninsert volue of c :");  
      scanf("%c",&c);  
      getchar();    // using getchar() to take '\n' from terminal
      printf("\ninsert volue of ch :");  
      scanf("%c",&ch);  
      getchar();  
      printf("\n c =%c && ch = %c",c,ch);  
 }  
OUTPUT :

No comments:

Post a Comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets