最近,我一直试图从这个网站学习c++。不幸的是,每当我试图运行其中一个代码示例时,我看到该程序打开了大约半秒钟,然后立即关闭。有没有办法阻止程序立即关闭,以便我能看到我的努力的成果?
当前回答
这里有个问题,不太明显。不知怎么的,我在程序的最后一行添加了一个调试断点。不知道我是怎么做到的,可能是在不同屏幕之间跳跃时错误地点击了鼠标。我在VS Code工作。
当我进行调试时,系统立即跳转到那个断点。没有错误消息,没有临时输出,什么都没有。我就想,程序是怎么通过我设置的所有断点的?我花了太长时间才想明白。
显然,系统将最后一行断点视为“第一个”停止。简单的解决方法?删除断点,哎呀!(此处插入前额。)
其他回答
对于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++称之为字符集)。
如果您正在使用Visual Studio,并且正在从IDE启动控制台应用程序:
按CTRL-F5(启动而不调试)将启动应用程序并保持控制台窗口打开,直到按下任何键。
这似乎很有效:
cin.clear();
cin.ignore(2);
如果您先清除缓冲区,那么当您读取下一个缓冲区时就不会有问题。 由于某些原因,sin .ignore(1)不起作用,它必须是2。
简单的
#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.
如果你使用的是Windows,为什么不直接从控制台运行这个程序呢?这样,程序结束后窗口仍保持打开状态。
[编辑]:当我使用KDevelop4时,IDE底部的一个选项卡中运行着一个完整的Bash实例(一个Linux CLI)。这就是我在这种情况下使用的方法。
推荐文章
- 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?