最近,我一直试图从这个网站学习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.
其他回答
而不是按下运行按钮,同时按CTRL和F5,它会给你按任意键继续消息。或者键入“(警告使用此仅用于测试而不是实际程序作为防病毒不喜欢它!!!!)”在你的主函数的末尾但是:(警告使用此仅用于测试而不是实际程序作为防病毒不喜欢它!!!!)
查看您的IDE在项目设置中是否有一个复选框,以便在程序终止后保持窗口打开。如果不是,使用std::cin.get();读取主函数末尾的一个字符。但是,请确保只使用基于行的输入(std::getline)或处理剩余的未读字符(std::ignore until newline),否则末尾的.get()将只读取之前未读的垃圾。
简单地把它放在代码的末尾:
而(1){}
这个函数将一直运行下去(或者直到您关闭控制台为止),并将防止控制台自己关闭。
我试着在最后放一个getchar()函数。但这并没有起作用。所以我所做的就是一个接一个地添加两个getchar()函数。我认为第一个getchar()吸收了您在最后一个数据输入后按下的Enter键。所以尝试添加两个getchar()函数而不是一个
我在程序的最后一个返回0处设置了断点。它工作得很好。
推荐文章
- 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?