Saturday, March 12, 2011

Reading and discarding characters in scanf()

Reading and discarding characters from the input stream

1.
int main()
{
int month,day,year;

printf( "Enter a date in the form mm-dd-yyyy: " );
scanf( "%d%*c%d%*c%d", &month, &day, &year );

printf( "month = %d day = %d year = %d\n\n", month, day, year );
return 0;
}

Output:
Enter a date in the form mm-dd-yyyy:03-12-2011
month = 03 day = 12 year = 2011

Explanation:
as we write the input:03-12-2011
scanf discards the character - because we used %*c to discard that character...there can be any character at the place of -...............

2.
int main()
{
int i,j;

printf( "Enter the numbers: " );
scanf( "%d/*/%d", &i,&j );

printf( "%d %d", i,j);
return 0;

}

output:
Enter the numbers:4/*/5
4 5

Explanation:
now we enter the numbers in this format 4/*/5 because scanf( "%d/*/%d", &i,&j ) consist /*/, and it discards this................ so i = 4 and j = 5..............

*****************************************

lets take one more example with field width and *

int main()

{

int a,b;

scanf("%d%*4c%d",&a,&b);

printf("a=%d,b=%d",a,b);

return 0;

}

/*before discussing its output.....firstly understand wht %*4c will do.......it will discard the 4 characters from the input string........*/

OUTPUT:

12abcd34

a=12

b=34

Explanation:

as the input string is 12abcd34.....the scanf start reading the characters 1..2..a.. as 'a' comes it start discarding the characters......n discard 4 characters continuously and then remaining characters i.e. 34 are in b variable....n suppose if d input string is 12abcde thn b has some garbage value........bcoz 'e' will not match with %d................