最近,我一直试图从这个网站学习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.
其他回答
如果您实际上是在Visual c++中调试应用程序,请按F5或工具栏上的绿色三角形。如果你不是真的调试它(你没有设置断点),按Ctrl+F5或选择菜单上的Start Without debugging(它通常在Debug菜单上,我同意这是令人困惑的)。它会更快一点,更重要的是,它会在结束时暂停,而无需更改代码。
或者,打开命令提示符,导航到exe所在的文件夹,并通过键入它的名称来运行它。这样,当它完成运行时,命令提示符不会关闭,并且您可以看到输出。我更喜欢这两种方法,而不是添加代码,在应用程序完成时停止它。
编辑:正如Charles Bailey在下面的评论中正确指出的那样,如果stdin中缓冲了字符,这将不起作用,而且真的没有好方法来解决这个问题。如果运行时附带调试器,John Dibling建议的解决方案可能是解决问题的最干净的解决方案。
也就是说,我把它留在这里,也许其他人会觉得它有用。在开发期间编写测试时,我经常使用它作为一种快速的方法。
在main函数的末尾,你可以调用std::getchar();
这将从stdin中获取单个字符,从而为您提供“按任意键继续”类型的行为(如果您确实想要“按任意键”消息,则必须自己打印一条)。
你需要为getchar添加#include <cstdio>。
简单地把它放在代码的末尾:
而(1){}
这个函数将一直运行下去(或者直到您关闭控制台为止),并将防止控制台自己关闭。
对于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++称之为字符集)。
我使用cin.get(),这是有效的,但有一天我需要使用另一个cin。get([数组变量])之前获取一个中间有空白字符的ling字符串。因此,cin.get()并没有避免命令提示符窗口关闭。最后我找到了另一种方法: 按CTRL+F5在外部窗口中打开,Visual Studio不再对其进行控制。只会在最后的命令运行后询问关闭。
推荐文章
- 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?