最近,我一直试图从这个网站学习c++。不幸的是,每当我试图运行其中一个代码示例时,我看到该程序打开了大约半秒钟,然后立即关闭。有没有办法阻止程序立即关闭,以便我能看到我的努力的成果?


当前回答

你所要做的就是为x设置一个变量,然后在返回0之前输入这个;

cout<<"\nPress any key and hit enter to end...";
cin>>x;

其他回答

使用#include "stdafx.h" & system("pause");就像下面的代码一样。

#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
    std::cout << "hello programmer!\n\nEnter 2 numbers: ";
    int x, y;
    std::cin >> x >> y;
    int w = x*y;
    std::cout <<"\nyour answer is: "<< w << endl;
    system("pause");
}

你也可以坚持

while(true)
    ;

or

for(;;)
    ;

最后。

对于Visual Studio(并且只有Visual Studio),下面的代码片段给了你一个'wait For keypress to continue'提示,它真正地等待用户显式地按下一个新键,首先刷新输入缓冲区:

#include <cstdio>
#include <tchar.h>
#include <conio.h>

_tprintf(_T("Press a key to continue "));
while( _kbhit() /* defined in conio.h */ ) _gettch();
_gettch();

注意,这里使用了tchar.h宏来兼容多个“字符集”(vc++称之为字符集)。

好吧,我猜你在Windows上使用Visual Studio…为什么?因为如果你在某种Linux操作系统上,那么你可能会从控制台运行它。

不管怎样,你可以像其他人建议的那样在程序的末尾添加一些无用的东西,或者你可以只按CTRL + F5(不用调试就开始),Visual Studio在完成后就会离开控制台。

如果你想运行调试版本而不给你的代码添加垃圾,另一个选择是打开控制台窗口(开始->运行-> cmd)并导航到调试输出目录。然后,只需输入可执行文件的名称,它就会在控制台中运行调试程序。然后你可以使用Visual Studio的attach to process或者其他你想要的东西。

你甚至可以在main()函数的开头声明一个整数(比如int a;),然后输入std::cin >> a;就在返回值之前。因此,程序将一直运行,直到你按下一个键并进入。