[英]AllocConsole with 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();
}
我將嘗試通過發布您發布的代碼來回答您的問題,但添加適當的#include
文件。
#include <windows.h>
#include <cstdio>
int main()
{
BOOL f = AllocConsole();
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
使用Visual Studio 2013,有關於“危險功能”的警告,但代碼編譯成功。 因此,您應該按原樣使用上面的代碼並進行編譯。 如果有錯誤,請更新您的問題。
編輯:由於您更新了問題,我可以看到這些錯誤的唯一原因是因為該代碼必須位於功能塊內。 你不能像這樣只有自己的代碼。
這實際上就是你發布的內容:
#include <windows.h>
#include <cstdio>
BOOL f = AllocConsole();
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
由於上述原因,這將無法成功編譯。 我得到的錯誤與您的錯誤類似。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.