Search code examples
cgetchar

getchar() returns immediately


I'm programming C in Visual Studio 2013 Express for Desktop, and when I use getchar() it terminates immediately.

Here's the code:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main()
{
    int num1, num2;
    printf("Enter first number: ");
    scanf("%d", &num1);
    printf("Enter second number: ");
    scanf("%d", &num2);
    printf("Result: %d\n", num1 + num2);
    printf("Press any key to exit...");
    getchar();
}

After the last string is printed, the program exits immediately without waiting for any key press, even though I've used getchar().

Should getchar() wait for a key press (character input), and the move on? Why does it automatically goes on and exits the program, without waiting for key press?


Solution

  • The solution is to call getchar(); twice in the end, or to use fgets(); instead.

    The problem is, that when you enter a char on the console, you do in fact enter an additional newline each time.