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>
usingnamespace std;
int main()
{
int num;
cout << "Enter a number: ";
cin >> num;
getchar();
cout << "You entered " << num << ".";
getchar();
return 0;
}
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.