c++ - AllocConsole 与 Visual Studio 2013

标签 c++ visual-studio-2013

我试图让一个控制台寡妇与主应用程序窗口一起运行,显然这应该可以工作,并且控制台窗口确实会显示,但以“freopen”开头的 3 行代码停止编译,并出现“缺少”等错误类型说明符”。

 #include <stdio.h>
 #include "Windows.h"
 #include "Wincon.h"

 BOOL f = AllocConsole();
 freopen("CONIN$", "r", stdin);
 freopen("CONOUT$", "w", stdout);
 freopen("CONOUT$", "w", stderr);

删除 3 行并将其替换为:

 OutputDebugString(L"\n");

正如我认为应该用来设置窗口中的文本给出以下错误:

 1>main.cpp(13): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
 1>main.cpp(13): error C2365: 'OutputDebugStringW' : redefinition; previous definition was 'function'
 1>          C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\include\winbase.h(7733) : see declaration of 'OutputDebugStringW'
 1>main.cpp(13): error C2440: 'initializing' : cannot convert from 'const wchar_t [2]' to 'int'
 1>          There is no context in which this conversion is possible

搜索答案会得到很多结果,但他们通常会说:

AllocConsole();
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);

这对我来说不起作用,所以我错过了什么?

最佳答案

我个人在需要控制台和 GUI 的程序中使用它。您可以尝试一下,看看它是否适合您。它使用 iostream 而不是 freopen.

它不能回答您的问题,但它是实现同一目标的一个想法或另一种方式。

#include <iostream>
#include <windows.h>
#include <fstream>
#include <streambuf>

class Console
{
    private:
        std::wstreambuf *CinBuffer, *CoutBuffer, *CerrBuffer;
        std::wfstream ConsoleInput, ConsoleOutput, ConsoleError;

    public:
        Console();
        Console(const Console &console) = delete;
        Console(Console&& console); = delete;
        ~Console();

        Console& operator = (const Console& other) = delete;
        Console& operator = (Console&& other) = delete;

        template<typename T>
        void operator << (const T &Data) {std::wcout<<Data<<std::flush;}
};


Console::Console()
{
    if (AllocConsole())
    {
        CinBuffer = std::wcin.rdbuf();
        CoutBuffer = std::wcout.rdbuf();
        CerrBuffer = std::wcerr.rdbuf();
        ConsoleInput.open("CONIN$", std::ios::in);
        ConsoleOutput.open("CONOUT$", std::ios::out);
        ConsoleError.open("CONOUT$", std::ios::out);
        std::wcin.rdbuf(ConsoleInput.rdbuf());
        std::wcout.rdbuf(ConsoleOutput.rdbuf());
        std::wcerr.rdbuf(ConsoleError.rdbuf());
    }
}

Console::~Console()
{
    ConsoleInput.close();
    ConsoleOutput.close();
    ConsoleError.close();
    std::wcin.rdbuf(CinBuffer);
    std::wcout.rdbuf(CoutBuffer);
    std::wcerr.rdbuf(CerrBuffer);
    FreeConsole();
}

关于c++ - AllocConsole 与 Visual Studio 2013,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28653381/

相关文章:

c++ - 从同一个文件中读取字符串和整数

c++ - 类似于 "if constexpr"但用于类定义

c - 将c程序从linux迁移到windows

visual-studio-2013 - Nuget 包管理器控制台未找到错误

c# - 生成带有格式的文档文本

c++ - 创建指针的c++ vector

c++ - C++11 中 std::less 的模板特化,使用模板

c++ - 如何对单个相机的多个图像中的点进行三角测量?

git - vim 的电力线是否有 VS 模拟?

c++ - 在 QLabel/QGraphicsView 中显示 Dicom 图像