THAT'S REALLY INTERESTING
wrong code
#include <stdio.h>
int main( )
{
char another;
int num;
do
{
printf("Enter a number: ");
scanf("%d", &num);
printf("\nWant to enter another number y/n ");
scanf("%c", &another);
}while(another == 'y');
return 0;
}
OUTPUT: Enter a number: 23
Want to enter another number y/n C:\Users\Shivam Singh\Documents\Let's C\From Book\Ch3>
To differentiate between the wrong and right code please look at the %c. The only difference in both the codes is a space which is just before %c in the right code.
right code
#include <stdio.h>
int main( )
{
char another;
int num;
do
{
printf("Enter a number: ");
scanf("%d", &num);
printf("\nWant to enter another number y/n ");
scanf(" %c", &another);
}while(another == 'y');
return 0;
}
OUTPUT: Enter a number: 23
Want to enter another number y/n y Enter a number: 54
Want to enter another number y/n n
The space is required for scanf()
to consume the pending newline left in stdin
by the previous scanf()
that read a number and stopped consuming characters right after the last digit. Without this space, scanf()
will store the next byte into another
, most likely the newline that was typed by the user to submit the number.
Note that you should also test the return values of scanf()
to detect invalid input or premature end of file.