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

前端 未结 10 651
悲哀的现实
悲哀的现实 2020-11-22 16:22

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:

#incl         


        
相关标签:
10条回答
  • 2020-11-22 17:19

    Can getchar be getting your carriage return that you enter after the 1?

    0 讨论(0)
  • 2020-11-22 17:24

    while reading other answers it just came to me that you can use scanf("%d\n",&n); instead of scanf("%d",&n); to remove new line from buffer. I haven't checked this out though.

    Hope it works :D

    0 讨论(0)
  • 2020-11-22 17:25
    #include <stdio.h> 
    #include<conio.h>
    void main() 
    { 
        int value; 
        printf("1. option 1.\n2. option 2.\n3. option 3.\n4. Exit\n\nMake 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; 
        } 
        getch(); 
    } 
    
    0 讨论(0)
  • 2020-11-22 17:26

    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.

    0 讨论(0)
提交回复
热议问题