Why Extra getchar() Calls?

Why is it that the console window automatically closes if I don't have a getchar() call after the "cin >> num;" line? Shouldn't just one getchar() call before ending the program be sufficient? I'm using Visual Studio 2015 to compile it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
using namespace std;

int main()
{
  int num;
  cout << "Enter a number: ";
  cin >> num;
  getchar();
  cout << "You entered " << num << ".";
  getchar();

  return 0;
}
Last edited on
Calling getchar() blocks the console from closing. In other case, VS built programs simply run, do what they need to do and then close.

More stupid, and unrecomended solution would be system("pause")
When you use the formatted extraction operator (>>) on a int, it leaves an extra newline in the buffer. This means that your getchar() on line 9 will get that extra newline. If you didn't have it there, you will instead get it on line 11, meaning your program won't stop.
Topic archived. No new replies allowed.