-3

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?

Mat
  • 202,337
  • 40
  • 393
  • 406
Travier
  • 205
  • 2
  • 9
  • 2
    'cos there's a char still left in the input buffer. – Martin James May 07 '14 at 12:08
  • 1
    This question comes up on StackOverflow about once a day. I'll see if I can find some duplicates... – Paul R May 07 '14 at 12:08
  • I think this is a repetition of [using getch() to hold command prompt open Visual C++ 2010 ](http://stackoverflow.com/questions/7502476/using-getch-to-hold-command-prompt-open-visual-c-2010) – DOOM May 07 '14 at 12:09

1 Answers1

-1

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.

Theolodis
  • 4,977
  • 3
  • 34
  • 53