I was recently running a c program in my PC. It have a for loop in which some char d is scanned. The for loop runs for 3 times. During each running it prints the the count of running and then scans the value of char d. The program is as follows
#include<stdio.h>
int main(){
int f;
char d;
for(f=0;f<3;f++){
printf("Choice %d\n", f);
scanf("%c", &d);
}
return 0;
}
Now the trouble is that when I run the program, the for skips the scanf part when f is 1. Now if i changed the code as follows
#include<stdio.h>
int main(){
int f;
int d;
for(f=0;f<3;f++){
printf("Choice %d\n", f);
scanf("%d", &d);
}
return 0;
}
Now the program works fine. and scanf is executed for every iteration of for loop.
What does seem to be the problem here? I mean when d is of type int it works fine, but when d is of type char it does not work correctly.
The problem is that when you enter a character for scanf("%c", &d); , you press the enter key. The character is consumed by the scanf and the newline character stays in the standard input stream( stdin ).
This happens because every scanf() leaves a newline character in a buffer that is read by the next scanf. How to Solve the Above Problem? We can make scanf() to read a new line by using an extra \n, i.e., scanf(“%d\n”, &x) . In fact scanf(“%d “, &x) also works (Note the extra space).
%s tells scanf to discard any leading whitespace, including newlines. It will then read any non-whitespace characters, leaving any trailing whitespace in the input buffer.
If you use %c , you'll print (or scan) a character, or char. If you use %d , you'll print (or scan) an integer. printf("%d", 0x70);
You have to change
scanf("%c", &d);
to
scanf(" %c", &d);
^
|
Otherwise, scanf()
will consider the previously entered ENTER
key press.
Note:
ENTER key press generates a \n
, which is a vaild input for %c
format specifier. Adding a space before %c
tells scanf()
to ignore all leading whitespace-like inputs (including that previously stored \n
) and read the first non-whitespace character from stdin
.
As for the case with %d
format specifier, it consumes (and ignores) any leading whitespace-like inputs before scanning for numeric inputs, so the second case does not suffer any issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With