我开始在Visual c++和我想知道如何保持控制台窗口。

例如,这将是一个典型的“hello world”应用程序:

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World";
    return 0;
}

我漏了哪一行?


当前回答

我的观点:

选择1:在main()的末尾添加断点

选择2:在返回0之前添加这段代码:

std::cout << "Press ENTER to continue..."; //So the User knows what to do
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

对于std::numeric_limits,您需要包含<iomanip>

其他回答

你可以把 keep_window_open (); 在返回之前,这里有一个例子

int main()
{
    cout<<"hello world!\n";
    keep_window_open ();
    return 0;
}

实际上,真正的解决方案是项目模板本身的选择。 你必须在旧的VS中选择Win32控制台应用程序,或者先填写项目名称,然后双击Windows桌面向导,然后选择Win32控制台应用程序。然后在此时选择空项目。然后,这允许原始提问者真正想要的东西,而无需添加额外的停止点和保持代码。 我也遇到过这个问题。答案也在MSDN网站上。

另一种选择是使用

#include <process.h>
system("pause");

虽然这不是很可移植,因为它只能在Windows上工作,但它会自动打印

按任意键继续…

标准的方法是在return语句之前使用cin.get()。

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World";
    cin.get();
    return 0;
}

只需在代码的末尾添加system("pause"),然后像这样返回0

#include <stdlib.h>

int main()
{
    //some code goes here
    system("pause")
    return 0;
}