The enter key (also called newline) matters. When you type something using the keyboard, you have to press the Enter key at the end.
We tend to ignore the Enter key, because it’s not what we’re interested in. However, it’s still there. We have to deal with it.
When reading characters, make sure that you’ve accounted for the Enter key:
char cmd; // single-character command char enter; // dump the enter key here double value; printf("Enter a command: "); scanf("%c%c", &cmd, &enter); printf("Now a number: "); scanf("%lf%c", &value, &enter);
This reads the command into cmd
, and reads the Enter key into enter
,
where it is ignored.
If all that your program reads are numbers, then you
don’t have to worry about the Enter key. That’s because scanf
is smart when reading numbers, and skips over leading whitespace
(spaces, tabs, and the Enter key).
However, if your program is reading both characters and numbers, then you have to deal with the Enter key.
Here’s how to avoid having an enter
variable:
char cmd; // single-character command printf("Enter a command: "); scanf("%c%*c", &cmd);
*
in %*c
means “Don’t save that character that
we read—throw it away.”
enter
variable, because we’re not
saving the Enter key anywhere.
%d
, %f
, or %s
, is redundant, but ok.
%d
, %f
, and %s
automatically skip leading whitespace.
%c
does not.
Here’s another technique:
char cmd; printf("Enter a command: "); scanf(" %c", &cmd);
%c
?
%c
.
Consider this poor code:
char cmd; printf("Enter a command: "); scanf(" %c ", &cmd); // BAD CODE
scanf
supposed to know how much whitespace you’re going
to type?
Modified: 2017-12-08T12:54 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |
![]() |