Monday, May 27, 2013

discard the unread new line character from input buffer


Today while going through a simple program to understand the behavior of scanf and gets , I was stuck in a very interesting concept usually occurring  with scanf .

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str1[10],str2[10],str3[10],str4[10],str5[50],c;
    scanf("%s%s%s%s",str1,str2,str3,str4);
    printf("str1 : '%s'\n",str1);
    printf("str2 : '%s'\n",str2);
    printf("str3 : '%s'\n",str3);
    printf("str4 : '%s'\n",str4);
    
    gets(str5);
    printf("str5 : '%s'",str5);
    return 0;
}
--------------------------------------------------------------------------------------------- 
Input :

    Alice in wonder land

   

Ouptut:

    str1 : 'Alice'

    str2 : 'in'

    str3 : 'wonder'

    str4 : 'land'

    str5 : ''
 
 
We see that program does not wait for us for giving input for str5 . 



Reason :

This is because when a user presses Enter , two characters are added to the input buffer

1)Enter key (ASCII code 13)

2)newLine character(\n) (ASCII code 10)



At the gets statement , the input buffer contains still contains "\n" , new line character . 
As a result , str5 contains only the newLine character and goes the printf statement , 
printing the undesired value of str5.
To avoid this thing , we can do one of the following things 



1)Use of "%*c" 
 
scanf("%s%s%s%s%*c",str1,str2,str3,str4);
Adding "%*c" consumes the next character in the input buffer . As a result , the "\n" is consumed, 
and hence no longer remains in the input buffer . This is one of the ways we can avoid the trailing "\n" 
from the input buffer .



2)Use of getchar() , getc() 

After the four printf() statements we can add  getchar() or getc() . These function gets the next unread 
character from the input buffer . Hence , the newLine character does not remain in the input buffer and we 
can  input the string for str5 without any difficulty.