i recently wrote a program in C that allows a user to enter a letter which is later identified with the help of the coding of the program and displays an output mentioning if the entered letter is A , B or something else.
Though this is a simple program i found an error that surprised me after compilation.
the coding does not stop at the scanf and ask the user to enter a value.
the coding is as follows,
// THIS PROGRAM SCANS A LETTER AND AND DETERMINES IF THE ENTERED LETTER IS
//EQUAL TO A , B or SOMETHING ELSE
// AND PRINTS A MESSAGE
// QQQ : WHY DOES THE DEFAULT STATEMENT EXECUTE TWO TIMES???
//i.e. WHY DOES IT READ THE NULL CHARACTOR TOO?if we enter letter 'A' and
//press enter,it reads the enter too! i.e. it reads the '\n' provided by the
//enter
#include <stdio.h>
#include <math.h>
int main () {
char a;
do {
printf ( "Enter a letter for char 'a' : " );
scanf ("%c" ,&a );
switch (a) {
case 'a' :
printf ( " AAA ");
printf ("\n\n\n");
break;
case 'b' :
printf ( " BBB ");
printf ("\n\n\n");
break;
default :
printf ( " the default statement excecuted");
printf ("\n\n\n");
break;
}
} while ( 1);
return 0;
}
After a cople of days of hard work, i found the reason( upto my best knowledge) for this error. the reason is that the function SCANF buffers the A and the "enter button" i.e. \n i press in the console screen as a another charactor.
thus it does not let the program to go to the TOP (start of the while loop) till its buffered variables finish.
thus it will execte printf ( " the default statement excecuted"); TWO times!
but according to the study meterial you provided
ref to
http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
it says
" ..the function will read and ignore any whitespace characters (this includes blank spaces and the newline and tab characters) which are encountered before the next non-whitespace character. This includes any quantity of whitespace characters, or none.."
now this conflicts with results but cant think of another solution.
Help at this level from you will be greatly appreciated.
thank you