c++encodingconsolestdoutfreopen

Console outputs gibberish code after re-redirecting stdout to CON


When I use C++ to invoke Python program output (By system command with parameters), it outputs gibberish code at the end of line. After that, I couldn't input any character (Include Backspace and Enter), it displays a hollow square.

Console screenshot:

Whole function code: (Uses file process)

freopen("WCH_SYSTEM.tmp", "w", stdout);
system(("TRANS -i \"" + str + "\" > WCH_TRANS.tmp").c_str());
freopen("CON", "w", stdout);
Sleep(500);
ifstream fin("WCH_TRANS.tmp");
fin >> info;
cout << info << endl;
DeleteFile("WCH_SYSTEM.tmp");

Solution

  • After repeated inspection, I have found that freopen() can cause these encoding problems.

    You can redirect the output of the function (NOT FREOPEN!!!) to a temporarily file like this.

    DO NOT USE FREOPEN LIKE THIS! THIS MAY CAUSE UNEXPECTED BEHAVIOR.

    freopen("CON", mode, handle);
    

    This is correct:

    system(("TRANS -i \"" + str + "\" > WCH_TRANS.tmp").c_str());
    Sleep(500);
    ifstream fin("WCH_TRANS.tmp");
    fin >> info;
    cout << info << endl;
    DeleteFile("WCH_TRANS.tmp");
    

    I'm using TDM-GCC64 on Windows, maybe this issue only appear on this compiler.