给自己的程序添加一个控制台
有这个必要么?有!在调试的时候,通过控制台输出调试信息,可以实时跟踪程序的运行情况,比看日志文件要便捷。。。
代码如下:
#include <iostream> #include "conio.h" #include <wincon.h> #include <fcntl.h> #include <io.h> #include <fstream> using namespace std; using std::ios; bool RedirectIoToConsole (); bool AllocNewConsole() { // If this is already a console app we don't need to call // RedirectToConsole(). AllocConsole() fails if this process // already has a console. return (AllocConsole() && RedirectIoToConsole()); } bool RedirectIoToConsole () { HANDLE hStdHandle; int nConHandle; // redirect unbuffered STDOUT to the console hStdHandle = GetStdHandle (STD_OUTPUT_HANDLE); nConHandle = _open_osfhandle ((long)hStdHandle, _O_TEXT); *stdout = *_fdopen (nConHandle, "w"); setvbuf (stdout, NULL, _IONBF, 1024); // redirect unbuffered STDIN to the console hStdHandle = GetStdHandle (STD_INPUT_HANDLE); nConHandle = _open_osfhandle ((long)hStdHandle, _O_TEXT); *stdin = *_fdopen (nConHandle, "r"); setvbuf (stdin, NULL, _IOLBF, 1024); // redirect unbuffered STDERR to the console hStdHandle = GetStdHandle (STD_ERROR_HANDLE); nConHandle = _open_osfhandle ((long)hStdHandle, _O_TEXT); *stderr = *_fdopen (nConHandle, "w"); setvbuf (stderr, NULL, _IONBF, 1024); // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog // point to console as well ios::sync_with_stdio(); return true; }
然后在程序初始化(或者其他你认为合适的地方)调用AllocNewConsole()函数,该函数调用后就多了一个控制台,你就可以使用printf()函数输出调试信息了,当然如果程序本身就是控制台形式的,那就没必要了。