34

有没有什么情况下std::cout << "hello"不工作?我有 ac/c++ 代码,但是std::cout不打印任何内容,甚至不打印常量字符串(例如“hello”)。

有什么方法可以检查是否cout能够/无法打开流?有一些成员函数,如good(), bad(), ... 但我不知道哪一个适合我。

4

4 回答 4

54

确保刷新流。这是必需的,因为输出流是缓冲的,除非您自己手动刷新缓冲区,否则您无法保证何时刷新缓冲区。

std::cout << "Hello" << std::endl;

std::endl将输出换行符并刷新流。或者,只会std::flush进行冲洗。也可以使用流的成员函数完成刷新:

std::cout.flush();
于 2013-02-13T16:32:08.630 回答
11

std::cout 不适用于 GUI 应用程序!

特定于 MS Visual Studio:当您想要一个控制台应用程序并使用 MS Visual Studio 时,将项目属性“链接器 -> 系统 -> 子系统”设置为控制台。在 Visual Studio 中创建新的 Win32 项目(用于本机 C++ 应用程序)后,此设置默认为“Windows”,这会阻止 std::cout 将任何输出放到控制台。

于 2018-12-17T10:29:59.203 回答
6

由于缓冲(您正在编写的内容最终在缓冲区中而不是在输出中),这很可能std::cout不起作用。std::cout

您可以执行以下操作之一:

  • 显式刷新std::cout

    std::cout << "test" << std::flush; // std::flush is in <iostream>
    

    std::cout << "test";
    std::cout.flush(); // explicitly flush here
    

    std::cout << "test" << std::endl; // endl sends newline char(s) and then flushes
    
  • 改为使用std::cerrstd::cerr没有缓冲,但它使用不同的流(即,如果您对“查看控制台上的消息”感兴趣,则第二种解决方案可能不适合您)。

于 2013-02-13T16:40:45.543 回答
6

要有效地禁用缓冲,您可以调用它:

std::setvbuf(stdout, NULL, _IONBF, 0);

或者,您可以调用您的程序并在命令行中禁用输出缓冲:

stdbuf -o 0 ./yourprogram --yourargs

请记住,出于性能原因,通常不会这样做。

于 2016-05-26T14:30:36.440 回答