开发者

a simple question about getchar() usage?

When searching for everything about getchar() function in this really great site, I found this post: Why doesn't getchar() wait for me to press enter after scanf()?

#include <stdio.h>

int 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;
    }
    getchar();//here is the question,why it's useful ?
    return 0;
}

I understand the whole program, and I understand that each time it is called, getchar reads the next input character from a text stream and returns that as its value. That is, after

c = getchar();

the variable c contains the next character of input. The characters normally come from the keyboard.

But here is the question: why did the开发者_高级运维 programmer call getchar() at the end of the program?


this practice is used especially for console applications, that way you force the program to not stop until you press a key so you can read the output. Usually the console closes when the program execution ends


The last getchar() function is there in order for the application to wait for a keypress before exit.


Generally in console apps, when you work in an IDE and run the code, a terminal window pops up runs the code, and as soon as the main function ends the terminal window also vanishes, and the users cannot see the last output. We need to make some way that the screen waits. One way is to make the program from being terminated by waiting for an input. Some people uses unbuffered input function at the end, so whenever you press a key the function reads it and returns immediately. In this case you use getchar which is a buffered input function, in this case, when you have finished inspecting the screen, press any character and press enter which will return from the function and after that terminate the program. You could have used scanf or other ways to hold the screen too.

It is good for debugging, please remove it from final release.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜