Sunday, December 18, 2011

Problem in using scanf() before fgets() or gets() in C | Solution


Problem :

code :
#include <stdio.h> 
#include <string.h> 
int main() 
{ 
      int n; 
      char buff[100]; 
      memset(buff,0,sizeof(buff)); 
      printf("Enter a number:"); 
      scanf("%d",&n); 
      printf("You entered %d \n",n); 
      printf("\n Enter a name:"); 
      fgets(buff,sizeof(buff),stdin); 
      printf("\n The name entered is %s\n",buff); 
      return 0; 
}


output :


~/home $ ./aa  
Enter a number:123 
You entered 123  
 
 Enter a name: 
 The name entered is  
 
 ~/home $ ./aa  
Enter a number:123abc456 
You entered 123  
 
 Enter a name: 
 The name entered is abc456


As you can see above, I ran the executable twice and I got some weird results :

  1. In the first run, the execution did not stop at stdin when the fgets() API was being executed. So, I could not enter a name and hence no name was displayed.
  2. In the second run also the execution did not stop at stdin when fgets() API was being executed. So, I could not enter a name but the weirder part is that the last line of the output shows few final bytes of the input given to scanf() API being stored as the value of name.
---> Using fflush(stdin); may work in old compilers but not in new and advanced compilers like gcc.

Solution :

Code:
#include <stdio.h> 
#include <string.h> 
  int main() 
  { 
      int n; 
      char buff[100]; 
      memset(buff,0,sizeof(buff)); 
      printf("Enter a number:"); 
      scanf("%d",&n); 
      printf("You entered %d \n",n); 
      getchar(); 
      printf("\n Enter a name:"); 
      fgets(buff,sizeof(buff),stdin); 
      printf("\n The name entered is %s\n",buff); 
      return 0; 
  }
Lets look at the output :

Code:
~/home $ ./aa  
Enter a number:123 
You entered 123  
 
 Enter a name: globalsoftbay 
 
 The name entered is globalsoftbay

Adding getchar() solves the problem. But I don't think it is ideal solution. If you people find this working / not working, just comment below. If anyone know the ideal solution, fee free to post.




If you enjoyed this post, make sure you subscribe to my RSS feed! Comments are encouraged

No comments:
Write comments