Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

c - Why doesn't getchar() wait for me to press enter after scanf()?

I am learning C and I'm using "getchar()" to stop the command windows so I can see the exercises am doing but it just doesn't work. heres a sample:

#include <stdio.h>

int main()
{
    int value;
    printf("1. option 1.
2. option 2.
3. option 3.
4. Exit

Make an option: ");
    scanf("%d", &value);
    switch (value)
    {
        case 1:
            printf("you selected the option 1.");
            break;
        case 2:
            printf("you selected the option 2.");
            break;
        case 3:
            printf("you selected the option 3.");
            break;
        case 4:
            printf("goodbye");
            break;
        default:
            printf("thats not an option");
            break;
    }
    getchar();
    return 0;
}

this is the output:

  1. option 1.
  2. option 2.
  3. option 3.
  4. Exit.

Make an option: 1

you selected the option 1.

Process returned 0 (0x0) execution time : 3.453 s

Press any key to continue.

Why doesn't it wait for the input of "getchar()"?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your scanf only ate the number but not the trailing newline. Putting a newline or white space after the %d will then give you the opposite problem, reading too far.

This is why people don't like scanf.

I would suggest reading an actual line (use fgets(3)) and then using sscanf() to scan the string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...