conio.h in visual studio

May 15, 2013 at 7:32pm
Hi, I wrote a simple program in Visual Studio 2012 to add 2 and 3. The program will not run without "conio.h" and _getch();, the exe window disppears as soon as the program is compiled. Can someone explain to me why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include <iostream>
#include <cmath>
#include "conio.h"

using namespace std;

int main ()

{
	int x = 1;
	int y = 2;
	int z = x + y;

	cout << z;

	_getch();

return 0;

}
May 15, 2013 at 7:37pm
First of all try the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main ()
{
	int x = 1;
	int y = 2;
	int z = x + y;

	cout << z;


	return 0;
}


and run it by pressing Ctrl + F5.

As for your question then the windows application that is MS IDE runs your code creating a console. As soon as your code finished executiong the IDE closes the console.
Last edited on May 15, 2013 at 7:37pm
May 15, 2013 at 7:43pm
Thank you. Yes the console disappears after running, however with conio.h and _getch it remains up. What do these functions do?
May 15, 2013 at 7:46pm
Function _getch checks keyboard buffer and if the user will pressed a key the function returns the control to the main and executing of the program will finished.
Header conio.h contains declaration of that function.
May 15, 2013 at 7:54pm
Before you get a ton of usefull replies, know just this - conio.h is not part of C++ as such, and in modern IDE, such as visual studio 2012 it is simply deprecated, and all examples of its use are getting a bit outdated.
Last edited on May 15, 2013 at 7:54pm
May 15, 2013 at 9:39pm
Thanks, so if I want the console to remain up I will add conio in my code. Lastly, is there a place visual studio stores the value of "z", which is 3, that I can see it without using the console. Like in MATLAB where you can type in the variable in the command line and see the result after the program ran.
May 15, 2013 at 11:04pm
Thanks, so if I want the console to remain up I will add conio in my code.

There are other ways to achieve the same aim. See this old thread for further info:

Console Closing Down
http://www.cplusplus.com/forum/beginner/1988/

Andy
Last edited on May 15, 2013 at 11:04pm
May 16, 2013 at 1:07am
Better yet

Keep the console open long enough to see your program's output
http://www.cplusplus.com/articles/iw6AC542/
Topic archived. No new replies allowed.