In the statement scanf ("%s", &check);
you're trying to scan a string and stuff it into a char. There are a couple of ways to fix this issue:
Quick fix: replace scanf("%s", &check)
with scanf (" %c", &check)
. Notice the whitespace in the format string: " %c"
, not just "%c"
. The %c
format specifier does not skip leading whitespace, so you have to include whitespace before the %c
in your format string to explicitly signal to scanf()
that you want to skip the leading whitespace. If you don't, then the following will happen:
the carriage return left in the input stream from the previous prompt Enter the resistance of Rheostat:
will be taken as the input character. check
will be assigned
.
Both if
conditions will fail; check
is neither Y
nor y
, neither N
nor n
.
The execution will return to the top of the while
loop for flag
, which is still zero. So the output regarding the appropriate values of ohm
and led
will be displayed again, and then the prompt for check
will be displayed again.
scanf()
will check the input stream again, this time reading the actual choice the user enters, and do the appropriate thing.
By including the leading whitespace in your format string, you will avoid this duplicate output.
A better fix: flush the input buffer after each call to scanf()
. Define a macro:
#define FLUSH while (getchar() != '
')
and after each call to scanf()
, type FLUSH;
. It's a lot safer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…