最近,我一直试图从这个网站学习c++。不幸的是,每当我试图运行其中一个代码示例时,我看到该程序打开了大约半秒钟,然后立即关闭。有没有办法阻止程序立即关闭,以便我能看到我的努力的成果?
当前回答
简单的
#include <cstdio>
int main(){
// code...
std::getchar();
std::getchar();
return 0;
}
for some reason there is usually 1 character possible to read with getchar already in stdin when you run a program. so the first getchar reads this character, and the second getchar waits for user (your) input before exiting the program. And after a program exits most of terminals, especially on Windows close terminal immediately. so what we aim to is a simple way of preventing a program from finishing after it outputs everything. Of course there are more complex and clean ways to solve this, but this is the simplest.
其他回答
以调试模式启动,使用F5运行代码 要停止你的控制台应用程序,不要点击红叉,而是按CTRL-break 你会在程序的最后碰到所有的断点。
查看您的IDE在项目设置中是否有一个复选框,以便在程序终止后保持窗口打开。如果不是,使用std::cin.get();读取主函数末尾的一个字符。但是,请确保只使用基于行的输入(std::getline)或处理剩余的未读字符(std::ignore until newline),否则末尾的.get()将只读取之前未读的垃圾。
我通常只在main()的右大括号上加一个断点。当程序以任何方式结束时,断点将出现,您可以ALT-Tab到控制台窗口以查看输出。
只需在返回0之前使用cin.ignore();两次
main()
{
//your codes
cin.ignore();
cin.ignore();
return 0;
}
thats所有
只需在程序的末尾添加以下内容。它将尝试捕获某种形式的用户输入,从而阻止控制台自动关闭。
cin.get();
推荐文章
- 如何禁用标准错误流的日志记录?
- c++ 11中的递归lambda函数
- 在c++中指针使用NULL或0(零)吗?
- 在c++中,如何将int值附加到字符串中?
- 就性能而言,使用std::memcpy()还是std::copy()更好?
- 为什么布尔值是1字节而不是1位?
- 四舍五入到一个数字的最接近倍数
- 为什么“System.out。”println“工作在Android?
- 模板默认参数
- c++ auto关键字。为什么它是魔法?
- c++操作符中的隐式类型转换规则
- 为什么c++需要一个单独的头文件?
- 如何有效地清除std::queue ?
- 在哪种情况下我使用特定的STL容器?
- Uint8_t不能用cout打印