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


当前回答

对于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++称之为字符集)。

其他回答

在任何exit()函数之前或main()中的任何return之前添加以下行:

std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(100000, "\n");

我只是这样做:

//clear buffer, wait for input to close program
std::cin.clear(); std::cin.ignore(INT_MAX, '\n');
std::cin.get();
return 0;

注意:只有在程序早期使用过cin时,才需要清除cin缓冲区。同样使用std::numeric_limits::max()可能比INT_MAX更好,但它有点啰嗦,通常没有必要。

只需在返回0之前使用cin.ignore();两次

main()
  {
  //your codes 

  cin.ignore();
  cin.ignore();

  return 0;
  }

thats所有

调用cin.get ();2次:

    //...
    cin.get();
    cin.get();
    return 0
}

你也可以试着这样做

sleep (50000);
cout << "any text" << endl;

这将保存您的代码50000m,然后打印消息并关闭。但请记住,它不会永远暂停。