[c++] How to output to the console in C++/Windows

When using iostream in C++ on Linux, it displays the program output in the terminal, but in Windows, it just saves the output to a stdout.txt file. How can I, in Windows, make the output appear in the console?

This question is related to c++ windows console sdl iostream

The answer is


I assume you're using some version of Visual Studio? In windows, std::cout << "something"; should write something to a console window IF your program is setup in the project settings as a console program.


Your application must be compiled as a Windows console application.


If you're using Visual Studio you need to modify the project property: Configuration Properties -> Linker -> System -> SubSystem.

This should be set to: Console (/SUBSYSTEM:CONSOLE)

Also you should change your WinMain to be this signature:

int main(int argc, char **argv)
{
    //...
    return 0;
}

The AllocConsole Windows API function will create a console window for your application.


There is a good solution

if (AllocConsole() == 0)
{
    // Handle error here. Use ::GetLastError() to get the error.
}

// Redirect CRT standard input, output and error handles to the console window.
FILE * pNewStdout = nullptr;
FILE * pNewStderr = nullptr;
FILE * pNewStdin = nullptr;

::freopen_s(&pNewStdout, "CONOUT$", "w", stdout);
::freopen_s(&pNewStderr, "CONOUT$", "w", stderr);
::freopen_s(&pNewStdin, "CONIN$", "r", stdin);

// Clear the error state for all of the C++ standard streams. Attempting to accessing the streams before they refer
// to a valid target causes the stream to enter an error state. Clearing the error state will fix this problem,
// which seems to occur in newer version of Visual Studio even when the console has not been read from or written
// to yet.
std::cout.clear();
std::cerr.clear();
std::cin.clear();

std::wcout.clear();
std::wcerr.clear();
std::wcin.clear();

First off, what compiler or dev environment are you using? If Visual Studio, you need to make a console application project to get console output.

Second,

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

should work in any C++ console application.


You don't necessarily need to make any changes to your code (nor to change the SUBSYSTEM type). If you wish, you also could simply pipe stdout and stderr to a console application (a Windows version of cat works well).


If you're using Visual Studio, it should work just fine!

Here's a code example:

#include <iostream>

using namespace std;

int main (int) {
    cout << "This will print to the console!" << endl;
}

Make sure you chose a Win32 console application when creating a new project. Still you can redirect the output of your project to a file by using the console switch (>>). This will actually redirect the console pipe away from the stdout to your file. (for example, myprog.exe >> myfile.txt).

I wish I'm not mistaken!


Whether to use subsystem:console or subsystem:windows kind of depends on whether how you want to start your application:

  • If you use subsystem:console, then you get all of the stdout written to the terminal. The trouble is that if you start the application from the Start Menu/Desktop, you (by default) get a console appearing as well as the application window (which can look pretty ugly).
  • If you use subsystem:windows, you won't get stdout/stderr even if you run the application from a DOS window, Cygwin, or other terminal.

If you want the middle way which is to output to the terminal IF the application was started in a terminal, then follow the link that Luke provided in his solution (http://dslweb.nwnexus.com/~ast/dload/guicon.htm)

For reference, I ran into this problem with an application that I want to run in either normal Windows mode or batch mode (that is, as part of a script) depending on command-line switches. The whole differentiation between console and Windows applications is a bit bizarre to Unix folks!


If using MinGW, add an option, -Wl,subsystem,console or -mconsole.


If you have a none-console Windows application, you can create a console with the AllocConsole function. Once created, you can write to it using the normal std::cout methods.


For debugging in Visual Studio you can print to the debug console:

OutputDebugStringW(L"My output string.");

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to console

Error in MySQL when setting default value for DATE or DATETIME Where can I read the Console output in Visual Studio 2015 Chrome - ERR_CACHE_MISS Swift: print() vs println() vs NSLog() Datatables: Cannot read property 'mData' of undefined How do I write to the console from a Laravel Controller? Cannot read property 'push' of undefined when combining arrays Very simple log4j2 XML configuration file using Console and File appender Console.log not working at all Chrome: console.log, console.debug are not working

Examples related to sdl

libpng warning: iCCP: known incorrect sRGB profile '"SDL.h" no such file or directory found' when compiling How to output to the console in C++/Windows

Examples related to iostream

'cout' was not declared in this scope How to read line by line or a whole text file at once? How to print Unicode character in C++? Why std::cout instead of simply cout? operator << must take exactly one argument How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT? Why is reading lines from stdin much slower in C++ than Python? How to print (using cout) a number in binary form? Why would we call cin.clear() and cin.ignore() after reading input? Reading a file character by character in C