CS156: Intro to C, Part I

Spring 2018

Enter Matters

See this page as a slide show

CS156: Enter Matters

The Enter Key Matters

made at imgflip.com

The Enter key (also called newline, or return) matters. When you type something using the keyboard, you have to press Enter at the end.

We tend to ignore Enter, because it’s not what we’re interested in. However, it’s still there. We have to deal with it.

The Straightforward Method

When reading characters, make sure that you’ve accounted for Enter:

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 Enter into the variable called enter, where it is ignored.

Sometimes You Can Ignore Enter

If all that your program reads are numbers, then you don’t have to worry about Enter. 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 Enter.

This Makes it a Bit Easier

Here’s how to avoid having an enter variable:

char cmd;           // single-character command

printf("Enter a command: ");
scanf("%c%*c", &cmd);

Spaces matter, too

Yet Another Way to Do It

Here’s another technique:

char cmd;
printf("Enter a command: ");
scanf(" %c", &cmd);

Don’t Get Space-Happy

Consider this poor code:

char cmd;
printf("Enter a command: ");
scanf(" %c ", &cmd);                // BAD CODE

User: Guest

Edit History Source

Modified: 2018-02-25T13:54

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building