为何C++编译生成的EXE文件运行后立即关闭,无法查看计算结果?
解决Windows下C++程序运行后立即关闭的问题
你的程序在Windows下双击运行时,输入第二个数字后窗口直接关闭,是因为程序执行完main函数的所有代码后就会立即退出,控制台窗口随之关闭,导致你来不及查看计算结果。以下是几种无需依赖命令提示符的解决方法:
方法1:添加输入等待代码
在输出结果后,添加等待用户输入的代码,让程序在用户按下回车键后再退出。注意要先清除之前输入留下的换行符,避免cin.get()直接读取到换行符而提前退出:
修改后的完整代码:
#include <iostream> using namespace std; int main() { int a, b; cout << "Please enter first number \n"; cin >> a; cout << "Please enter second number \n"; cin >> b; int z = a + b; cout << "Sum of these numbers are: " << z << endl; // 清除输入缓冲区的换行符 cin.ignore(); // 等待用户按下回车键 cin.get(); return 0; }
方法2:使用系统暂停命令
调用Windows的pause命令,让程序执行到此处时暂停,提示用户按任意键继续。需要包含<cstdlib>头文件:
修改后的完整代码:
#include <iostream> #include <cstdlib> // 包含system函数的头文件 using namespace std; int main() { int a, b; cout << "Please enter first number \n"; cin >> a; cout << "Please enter second number \n"; cin >> b; int z = a + b; cout << "Sum of these numbers are: " << z << endl; // 调用系统暂停命令 system("pause"); return 0; }
内容的提问来源于stack exchange,提问作者Doston
相关产品推荐
相关产品推荐

