Visual Studio 2010 conio.h

I'm trying to build a first simple program in Visual Studio 2010 in C++:

#include <iostream>

using namespace std;

int main() {
    cout << "Hello World!" << endl;
    return 0;
}

But it doesn't work as written (I don't see any output when I run it). The only way I can make it work is by adding #include <conio.h> and getch() . Why doesn't the program work without these two lines of code when compiled with Visual Studio 2010, when it does when compiled with other compilers?


The program you presented works just fine if run from within Visual Studio 2010. However, you might think that it doesn't work if you run it outside of Visual Studio (eg from Windows Explorer), because it prints "Hello World!" and then immediately terminates. To keep it open long enough to see the output when run that way, you might need to do something like waiting for user input, but the program itself is fine as it is and does what it would when compiled with any other compiler. Incidentally, if you compiled it with another compiler and then ran it from Windows Explorer, you would see the same behaviour - the issue is nothing to do with the compiler and everything to do with the way in which you're running the program. If you run the program from the Command Prompt (cmd), you'll see the output without having the problem of the window immediately closing.


This code does work in Visual Studio 2010. Your problem is something else: The console-window is closing so fast, that you don't see the output. That's also the reason why adding conio.h and getch() , cin or system("pause") will solve your problem temporary.

Try the following: Open a command line (cmd.exe), input the path to your compiled .exe file and press enter - you should see the output of your program then.


try:

int main() {
  cout << "Hello world!" << endl
  int a;
  cin >> a;

}

Explanation: I think what is happening is that your visual studio displays the result window which immediately disappears. To stop it from doing so, you can just ask user to enter something before program ends.

链接地址: http://www.djcxy.com/p/95570.html

上一篇: AABB碰撞响应(推回碰撞物体)

下一篇: Visual Studio 2010 conio.h