如何阻止 C++ 控制台应用程序立即退出? [英] How to stop C++ console application from exiting immediately?

查看:45
本文介绍了如何阻止 C++ 控制台应用程序立即退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我一直在尝试从本网站学习 C++.不幸的是,每当我尝试运行其中一个代码示例时,我都会看到该程序打开了大约半秒钟,然后立即关闭.有没有办法让程序立即关闭,以便我可以看到我的努力成果?

Lately, I've been trying to learn C++ from this website. Unfortunately whenever I try to run one of the code samples, I see that program open for about a half second and then immediately close. Is there a way to stop the program from closing immediately so that I can see the fruits of my effort?

推荐答案

正如 Charles Bailey 在下面的评论中正确指出的那样,如果 stdin,而且真的没有什么好的方法可以解决这个问题.如果您使用附加调试器运行,John Dibling 建议的解决方案可能是解决您问题的最干净的解决方案.

As Charles Bailey rightly points out in a comment below, this won't work if there are characters buffered in stdin, and there's really no good way to work around that. If you're running with a debugger attached, John Dibling's suggested solution is probably the cleanest solution to your problem.

也就是说,我会把它留在这里,也许其他人会觉得它有用.在开发过程中编写测试时,我经常使用它作为各种快速技巧.

That said, I'll leave this here and maybe someone else will find it useful. I've used it a lot as a quick hack of sorts when writing tests during development.

main 函数的末尾,您可以调用 std::getchar();

At the end of your main function, you can call std::getchar();

这将从 stdin 获取一个字符,从而为您提供按任意键继续"的行为(如果您确实想要按任意键"消息,您将有自己打印一个).

This will get a single character from stdin, thus giving you the "press any key to continue" sort of behavior (if you actually want a "press any key" message, you'll have to print one yourself).

getchar 需要#include .

这篇关于如何阻止 C++ 控制台应用程序立即退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆