2

I have a WinAPI/Win32 application. If I try to use cin/cout/cerr when it is run from a command prompt, it doesn't work. I tried switching the project type from Windows Application to Console Application, but the problem is that a console window appears when I run it normally by double-clicking the executable.

So my question is: Is there any way I can use cin/cout/cerr with the parent (calling) console window in a Win32 application? (I only want this behaviour if parameter /c or /? were passed, so if it is called with no arguments then no matter what it should launch the GUI).

5
  • If you want to use standard input and ouput, you need a console window. It's not clear what you are asking about here.
    – user2100815
    Oct 15, 2018 at 23:11
  • if I run the program from a console window, I want the program to output to that same console. cin, cout and cerr just don't seem to work. That is the problem I want to solve
    – DarkAtom
    Oct 15, 2018 at 23:15
  • If you create a console application, that is what it will do.
    – user2100815
    Oct 15, 2018 at 23:16
  • Yes, but when the program is run normally and is set as console app, it will display a console window in the background, which is something I don't want. I only want it to use a console when it is run from one.
    – DarkAtom
    Oct 15, 2018 at 23:21
  • So, to be clear, if the application is launched from the console, you want the output to go to that console. If the application is launched from something like explorer, you don't want a console at all?
    – user2100815
    Oct 15, 2018 at 23:27

1 Answer 1

7

A GUI app does not have a console window attached to it by default.

When a GUI app is run from a console process, the GUI app can use AttachConsole() to attach itself to the console.

Or, if the GUI app is not run from a console process, but still wants to use a console window, it can create its own console window using AllocConsole().

Once the GUI app is attached to a console, it can use GetStdHandle() to get handles to the console's STDIN/STDOUT, and then redirect cin/cout to use them (how is dependent on your particular STL implementation).

Or, you can ignore cin/cout and just use ReadConsole() and WriteConsole() directly instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.