2011-04-27 108 views
1

所以我有一个GUI程序,由于某种原因,它不让我使用printf()进行调试。 当我使用printf()时,出于某种原因它不会转到Visual Studio调试器。无论如何,我想让我自己的独立窗口在GUI打开时打开, 基本上能够将信息输入到控制台并与之通话。C++单独的命令行窗口?

例如:

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

任何人都知道如何做到这一点? 基本上创建一个命令行和交谈,所以我可以看到输出:

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

可能重复的[Windows C++:我怎样才能重定向调用fprintf中STDERR?](http://stackoverflow.com/questions/7664/ Windows的C-如何-可以-I-重定向-标准错误换的呼吁fprintf中) – 2011-04-27 00:46:30

回答

4

可以使用AllocConsole创建一个控制台,然后明确地写入到创建一个控制台(有几个方法,GetStdHandle和文件写将会工作)。您也可以使用OutputDebugString来写入VS输出窗口。

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 
} 

(伪代码,功能可能不完全正确)

编辑: 如果你只通过你的talk功能写到控制台,这将正常工作。如果你在整个代码中使用printf/cout,你一定要使用Ben的方法(重复使用简单得多)。

3

@peachykeen有一半的解决方案。如果你想printfcout工作,试试这个:

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