zoukankan      html  css  js  c++  java
  • 给自己的程序添加一个控制台

      有这个必要么?有!在调试的时候,通过控制台输出调试信息,可以实时跟踪程序的运行情况,比看日志文件要便捷。。。

      代码如下:

      

    #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()函数输出调试信息了,当然如果程序本身就是控制台形式的,那就没必要了。

  • 相关阅读:
    Alpha 冲刺 (1/10)
    软工实践 · 第七次作业
    福大软工 · 第八次作业(课堂实战)- 项目UML设计(团队)
    软工实践· 第六次作业
    软工实践作业五-结对作业二
    软工实践第四次作业
    软工实践第三次作业
    软工实践第二次作业
    SDN第一次上机作业
    SDN第一次作业——关于网络编程
  • 原文地址:https://www.cnblogs.com/yuohoo/p/3015870.html
Copyright © 2011-2022 走看看