std::cout won't print

夙愿已清 提交于 2019-12-17 03:43:18

问题


Is there any circumstance when std::cout << "hello" doesn't work? I have a c/c++ code, however the std::cout doesn't print anything, not even constant strings (such as "hello").

Is there any way to check if cout is able/unable to open the stream? There are some member functions like good(), bad(), ... but I don't know which one is suitable for me.


回答1:


Make sure you flush the stream. This is required because the output streams are buffered and you have no guarantee over when the buffer will be flushed unless you manually flush it yourself.

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

std::endl will output a newline and flush the stream. Alternatively, std::flush will just do the flush. Flushing can also be done using the stream's member function:

std::cout.flush();



回答2:


It is probable that std::cout doesn't work due to buffering (what you're writing ends up in the buffer of std::cout instead of in the output).

You can do one of these things:

  • flush std::cout explicitly:

    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
    
  • use std::cerr instead. std::cerr is not buffered, but it uses a different stream (i.e. the second solution may not work for you if you're interested in more than "see message on console").




回答3:


std::cout won't work on GUI apps!

Specific to MS Visual Studio: When you want a console application and use MS Visual Studio, set project property "Linker -> System -> SubSystem" to Console. After creating a new Win32 project (for a native C++ app) in Visual Studio, this setting defaults to "Windows" which prevents std::cout from putting any output to the console.




回答4:


To effectively disable buffering you can call this:

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

Alternatively, you can call your program and disable output buffering in the command line:

stdbuf -o 0 ./yourprogram --yourargs

Keep in mind this is not usually done for performance reasons.



来源:https://stackoverflow.com/questions/14858262/stdcout-wont-print

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!