cout fail when used cin after redirect console stream
<p>I want to redirect console streams to cin,cout and cerr. (its a gui application)
Well, I have written this class wich do this but when use cin, cout works no more.</p>

<p>GetLastError says me INVALID_HANDLE VALUE</p>

<p>Can you explain me how fix this ? 
Thanks</p>

<pre><code>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;

};
</code></pre>

<p>Class method:</p>

<pre><code>void Kconsole::CreateConsole( void ){

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

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

    this-&gt;err = true;
    return;        
}    

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

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

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

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

<p>Main function</p>

<pre><code>int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,intnCmdShow){

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

// CreateConsole Call

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

int n = 0;

cin &gt;&gt; n; // ok, get typed number
n++;

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

// here GetLastError says INVALID_HANDLE_VALUE

cerr &lt;&lt; "\n testing cerr" // cerr outputs in console " test finished" and "testing cerr"
}
</code></pre>
