1、#include <conio.h>
2、在需要開啟控制台窗口的地方調用
AllocConsole();//注意檢查返回值
3、在需要輸出調試的時候調用_cprintf等函數
如_cprintf("i=%d\n", i);
4、關閉控制台的時候調用
FreeConsole();
注意:上述方法在輸出中文時會出現亂碼,如果需要輸出中文,請使用下面的方法:
AllocConsole();
freopen( "CONOUT$","w",stdout);
printf("i的值為%d\n", i);
FreeConsole();
方法二:
#include <io.h>
#include <fcntl.h>
void InitConsoleWindow()
{
AllocConsole();
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
int hCrt = _open_osfhandle((long)handle,_O_TEXT);
FILE * hf = _fdopen( hCrt, "w" );
*stdout = *hf;
}
BOOL CHelloMFCDlg::OnInitDialog()
{
CDialog::OnInitDialog();
InitConsoleWindow(); // add
printf("str = %s\n ", "Debug output goes to terminal\n");
......
}