如何查看 "cout" 命令的输出?

What to do to see the output of "cout" command?

我从 C++(Visual Studio 2015 和 Windows 8.1)开始,使用这个简单的代码:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world" << endl;
    return 0;
}

但是,输出屏幕什么也没有!,我该怎么办?

提前致谢。

您的代码完全没问题,但程序目前只打印并在之后立即退出,因为这可能发生得非常快,您甚至可能看不到它,请尝试暂停它:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world" << endl;
    cin.get();
    return 0;
}

此外,请确保您的防病毒软件未阻止 Visual Studio。

在 Visual Studio 中,使用 Ctrl-F5 启动程序,它会 运行 并自动为您暂停。无需额外代码。

另一个解决方案,依赖于平台。我的回答是针对那些只需要测试暂停以进行调试的人。不推荐发布解决方案!

windows

#include <iostream>

int main()
{
    std::cout << "Hello world" << endl;
    system("pause");
    return 0;
}

linux (and many alternatives)

#include <iostream>

int main()
{
    std::cout << "Hello world" << endl;
    system("read -rsp $'Press enter to continue...\n'");
    return 0;
}

正在检测平台

我曾经在编程作业中这样做,确保这只发生在 windows:

#include <iostream>
int main()
{
    std::cout << "Hello world" << endl;
    #ifdef _WIN32
        system("pause");
    return 0;
}

这是 ifdef 宏和操作系统的一个很好的备忘单:http://sourceforge.net/p/predef/wiki/OperatingSystems/

您的代码很好,但是,如果您将其作为 cmd 程序执行,程序 window 将立即关闭,您甚至可能看不到输出。您可以通过"pausing"程序编写额外的代码来解决这个问题:

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    cout << "Hello world" << endl;
    system("PAUSE");
    return 0;
}

如果您不喜欢每次输入时都包含一个 windows.h 文件,您可以在代码末尾添加一个 "cin.get();"。但老实说,因为你只是一个初学者,我认为你应该尝试的最酷的方法不是使用 Visual Studio 来学习 C/C++ 而是安装 CodeBlocks(一个简单但有效的 IDE) 来写一些不那么长的代码。要知道,VS是用来做庞大复杂的项目和一些实用程序开发的。

程序在 return 0; 退出并在 window 关闭。在此之前,您必须暂停程序。例如,您可以等待输入。

这是我执行此操作的代码片段。它适用于 windows 和 linux。

#include <iostream>

using std::cout;
using std::cin;

// Clear and pause methods
#ifdef _WIN32
// For windows
void waitForAnyKey() {
    system("pause");
}

#elif __linux__
// For linux
void waitForAnyKey() {
    cout << "Press any key to continue...";
    system("read -s -N 1"); // Continues when pressed a key like windows
}

#endif

int main() {
    cout << "Hello World!\n";
    waitForAnyKey();
    return 0;
}