Hey
Hey

Reputation: 11

C++ separate command line window?

So I have a GUI program and for some reason it does not let me debug using printf(). When I use printf(), it does not go to the Visual Studio debugger for some reason.

Anyways, I wanted to make my own separate window that opens up when the GUI opens up, and basically be able to feed information into that console and talk to it.

For example:

void talk(std::string info){
//Add the value of info to the next line in the console
}

Anyone know how to do this? Basically create a command line and talk to it so I can see output:

CommandLine c;
c.talk("hey!");

Upvotes: 1

Views: 2312

Answers (2)

ssube
ssube

Reputation: 48247

You can create a console using AllocConsole to create a console, then write to that explicitly (there are a few methods, GetStdHandle and file write will work). You can also use OutputDebugString to write to the VS output window.

void makeConsole()
{
    AllocConsole();
    console = GetStdHandle(STD_OUTPUT_HANDLE);
}

void talk(std::string info)
{
    WriteFile(console, info.c_str(), info.length());  // To console
    OutputDebugString(info.c_str()); // To output window
}

(pseudo-code, functions may not be quite right)

Edit: If you're writing to the console only through your talk function, this will work fine. If you're using printf/cout throughout your code, you definitely want to use Ben's method (much simpler to use repeatedly).

Upvotes: 4

Ben Voigt
Ben Voigt

Reputation: 283624

@peachykeen has half the solution. If you want to make printf and cout work, try this:

AllocConsole();
freopen("CONOUT$", "w", stdout);

Upvotes: 3

Related Questions