最近,我一直试图从这个网站学习c++。不幸的是,每当我试图运行其中一个代码示例时,我看到该程序打开了大约半秒钟,然后立即关闭。有没有办法阻止程序立即关闭,以便我能看到我的努力的成果?
当前回答
好吧,我猜你在Windows上使用Visual Studio…为什么?因为如果你在某种Linux操作系统上,那么你可能会从控制台运行它。
不管怎样,你可以像其他人建议的那样在程序的末尾添加一些无用的东西,或者你可以只按CTRL + F5(不用调试就开始),Visual Studio在完成后就会离开控制台。
如果你想运行调试版本而不给你的代码添加垃圾,另一个选择是打开控制台窗口(开始->运行-> cmd)并导航到调试输出目录。然后,只需输入可执行文件的名称,它就会在控制台中运行调试程序。然后你可以使用Visual Studio的attach to process或者其他你想要的东西。
其他回答
我试着在最后放一个getchar()函数。但这并没有起作用。所以我所做的就是一个接一个地添加两个getchar()函数。我认为第一个getchar()吸收了您在最后一个数据输入后按下的Enter键。所以尝试添加两个getchar()函数而不是一个
如果你正在运行Windows,那么你可以执行system("pause >nul");或系统(“暂停”);。它执行一个控制台命令来暂停程序,直到您按下一个键。>nul阻止它说按任意键继续....
使用#include "stdafx.h" & system("pause");就像下面的代码一样。
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
std::cout << "hello programmer!\n\nEnter 2 numbers: ";
int x, y;
std::cin >> x >> y;
int w = x*y;
std::cout <<"\nyour answer is: "<< w << endl;
system("pause");
}
只需在程序的末尾添加以下内容。它将尝试捕获某种形式的用户输入,从而阻止控制台自动关闭。
cin.get();
简单的
#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.
推荐文章
- 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?