gpt4 book ai didi

c++ - 在重定向控制台流后使用 cin 时 cout 失败

转载 作者:太空宇宙 更新时间:2023-11-04 12:23:28 24 4
gpt4 key购买 nike

我想将控制台流重定向到 cin、cout 和 cerr。 (它是一个 GUI 应用程序)好吧,我已经编写了这个类来执行此操作,但是当使用 cin 时,cout 不再起作用。

GetLastError 告诉我 INVALID_HANDLE VALUE

你能解释一下如何解决这个问题吗?

Kconsole.h
class Kconsole
{

public:

Kconsole();
~Kconsole();

void CreateConsole( void );
void CloseConsole ( void );

private:


HANDLE hin;
HANDLE hout;
HWND hwnd;

bool closed;
bool err;

ofstream n_cout;
ofstream n_cerr; // new streams
ifstream n_cin;

streambuf* old_cout;
streambuf* old_cerr; // old streams
streambuf* old_cin;

};

类方法:

void Kconsole::CreateConsole( void ){

// create a console window
int ok = AllocConsole();

if ( ok == 0 ) // check console creation
{

this->err = true;
return;
}

// redirect cout to console window
this->old_cout = cout.rdbuf();
this->n_cout.open("CONOUT$");
cout.rdbuf( this->n_cout.rdbuf() );

// redirect cerr
this->old_cerr = cerr.rdbuf();
this->n_cerr.open("CONOUT$");
cerr.rdbuf( this->n_cerr.rdbuf() );

// redirect cin
this->old_cin = cin.rdbuf();
this->n_cin.open("CONIN$");
cin.rdbuf( this->n_cin.rdbuf() );

//// set title
SetConsoleTitle("Console");
this->hwnd = GetConsoleWindow();
//
//// get handles
this->hin = GetStdHandle(STD_OUTPUT_HANDLE);
this->hout = GetStdHandle(STD_OUTPUT_HANDLE);
return;}

主要功能

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,intnCmdShow){

// All application initialization as RegisterClass, CreateWindow...

// CreateConsole Call

cout << "\nTest string"; // ok, writes this in opened console

int n = 0;

cin >> n; // ok, get typed number
n++;

cout << "\n test finished"; // dont outputs nothing to console

// here GetLastError says INVALID_HANDLE_VALUE

cerr << "\n testing cerr" // cerr outputs in console " test finished" and "testing cerr"
}

最佳答案

我完全不明白你为什么要搞乱 std::cout 等。如果将 stdoutstderrstdin 重定向到控制台,则可以调用 std::ios::sync_with_stdio() 以确保 std::coutstd::cerrstd::cin 都正常工作。例如:

// redirect unbuffered STDIN to the console
intptr_t lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);
int hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
FILE *fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );

std::ios::sync_with_stdio();

这是一篇很棒的文章(带来源)explains这一切。

关于c++ - 在重定向控制台流后使用 cin 时 cout 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3681779/

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