我正在通过一本名为 C++ 初学者指南第二版 的书学习 C++。当我运行可执行文件时,它会显示半秒钟然后关闭。
我在 Windows 8.1 上使用 Microsoft Visual Studio Express 2013 for Windows Desktop。
代码如下:
*/
#include <iostream>
using namespace std;
int main()
{
cout << "C++ is power programming.";
return 0;
}
我只能在运行时看到文本,因为控制台关闭得太快了。
为什么程序关闭得这么快,我该如何阻止这种情况发生?
'Project1.exe' (Win32): Loaded 'C:\Users\Benjamin\Documents\Visual Studio 2013\Projects\Project1\Debug\Project1.exe'. Symbols loaded.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp120d.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcr120d.dll'. Cannot find or open the PDB file.
The program '[6908] Project1.exe' has exited with code 0 (0x0).
最佳答案
逐行检查你的程序:
int main()
{
这定义了程序的入口点,它返回的 int
将返回到程序启动的任何地方。
std::cout << "C++ is power programming."; // or just cout when you're using namespace std
这会将字符串文字 C++ is power programming.
打印到控制台。
return 0;
}
返回值0给调用者常用来表示成功(程序执行成功)。但是,如果您愿意,您可以返回其他内容(例如,如果您的程序计算出一些应该由调用者使用的值)。
因此,简而言之,您告诉您的程序向控制台打印一条消息然后返回,这正是它所做的。如果你想阻止程序在完成后立即关闭,你可以在 return 0
语句之前像这样:
std::cin.get(); // or just cin.get() when using namespace std
return 0;
std::cin.get()
所做的是等待用户输入;准备就绪后,按 Enter 键应该会结束您的程序。
关于c++ - 简单的 "Hello World"样式程序在执行开始后很快关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23725539/