gpt4 book ai didi

c++ - AllocConsole 与 Visual Studio 2013

转载 作者:行者123 更新时间:2023-12-03 12:50:42 28 4
gpt4 key购买 nike

我试图让一个控制台寡妇与主应用程序窗口一起运行,显然这应该可以工作,并且控制台窗口确实会显示,但以“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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com