最近,我一直试图从这个网站学习c++。不幸的是,每当我试图运行其中一个代码示例时,我看到该程序打开了大约半秒钟,然后立即关闭。有没有办法阻止程序立即关闭,以便我能看到我的努力的成果?
当前回答
使用#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");
}
其他回答
查看您的IDE在项目设置中是否有一个复选框,以便在程序终止后保持窗口打开。如果不是,使用std::cin.get();读取主函数末尾的一个字符。但是,请确保只使用基于行的输入(std::getline)或处理剩余的未读字符(std::ignore until newline),否则末尾的.get()将只读取之前未读的垃圾。
这似乎很有效:
cin.clear();
cin.ignore(2);
如果您先清除缓冲区,那么当您读取下一个缓冲区时就不会有问题。 由于某些原因,sin .ignore(1)不起作用,它必须是2。
和你的答案相似,只是极简主义的选择。
创建一个包含以下内容的批处理文件:
helloworld.exe
pause
然后使用批处理文件。
在代码结束之前,插入这行代码:
system("pause");
这将保持控制台,直到你按下一个键。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Please enter your first name followed by a newline\n";
cin >> s;
cout << "Hello, " << s << '\n';
system("pause"); // <----------------------------------
return 0; // This return statement isn't necessary
}
对于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++称之为字符集)。
推荐文章
- decltype(auto)的一些用途是什么?
- Shared_ptr转换为数组:应该使用它吗?
- Printf与std::字符串?
- 禁用复制构造函数
- 只接受特定类型的c++模板
- c#和Java中的泛型有什么不同?和模板在c++ ?
- console.log()和console.debug()的区别?
- 如何禁用标准错误流的日志记录?
- c++ 11中的递归lambda函数
- 在c++中指针使用NULL或0(零)吗?
- 在c++中,如何将int值附加到字符串中?
- 就性能而言,使用std::memcpy()还是std::copy()更好?
- 为什么布尔值是1字节而不是1位?
- 四舍五入到一个数字的最接近倍数
- 为什么“System.out。”println“工作在Android?