簡體   English   中英

如何在換行后將 std::cout 輸出帶回頂部

[英]How to bring std::cout output back to the top after a new line

我有以下菜單,應該根據用戶是否鍵入F1F2鍵來更新:

int main()
{
    bool f1 = false;
    bool f2 = false;
 
    while (true)    
    {
        std::cout << "[F1]:  " << (f1 ? "ON" : "OFF") << std::endl;
        std::cout << "[F2]:  " << (f2 ? "ON" : "OFF") << std::endl;
        std::cout << "[INS] to quit" << std::endl;

        if (GetAsyncKeyState(VK_INSERT) & 0x1)
            break;

        if (GetAsyncKeyState(VK_F1) & 0x1)
            f1 = !f1;
        
        if (GetAsyncKeyState(VK_F2) & 0x1)
            f2 = !f2;
        
        Sleep(100);
        cleanWindow();
    }

    return 0;
}

現在,我之前使用過system("cls")並且它工作“正常”,但有人告訴我我應該使用 Win32 API 來清理控制台,因此我創建了cleanWindow()如下所述這篇 MSVC 文章

DWORD cleanWindow()
{
    HANDLE hStdOut;

    hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

    // Fetch existing console mode so we correctly add a flag and not turn off others
    DWORD mode = 0;
    if (!GetConsoleMode(hStdOut, &mode))
    {
        return ::GetLastError();
    }

    // Hold original mode to restore on exit to be cooperative with other command-line apps.
    const DWORD originalMode = mode;
    mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;

    // Try to set the mode.
    if (!SetConsoleMode(hStdOut, mode))
    {
        return ::GetLastError();
    }

    // Write the sequence for clearing the display.
    // \x1b[2J is the code for clearing the screen and set cursor to home
    DWORD written = 0;
    PCWSTR sequence = L"\x1b[2J";
    if (!WriteConsoleW(hStdOut, sequence, (DWORD)wcslen(sequence), &written, NULL))
    {
        // If we fail, try to restore the mode on the way out.
        SetConsoleMode(hStdOut, originalMode);
        return ::GetLastError();
    }

    // To also clear the scroll back, emit L"\x1b[3J" as well.
    // 2J only clears the visible window and 3J only clears the scroll back.

    // Restore the mode on the way out to be nice to other command-line applications.
    SetConsoleMode(hStdOut, originalMode);
}

現在,問題是“菜單”位於命令提示符的末尾而不是開頭,就像system("cls")

輸出

我的問題是,我該如何解決這個問題? 如何將輸出帶回外殼頂部?

編輯:

我還編輯了cleanWindow()函數來編寫序列: \\033[2JL"\\033[H"WriteConsoleW() ,它有效,但我仍然像使用system("cls") ,這是我試圖避免的。

SetConsoleCursorPosition ,您可以使用SetConsoleCursorPosition將光標位置設置回左上角。

還有ANSI 轉義碼(類似於您用來清除屏幕的轉義碼),可以讓您重新定位光標。

"\033[r;cH"

r替換為要移動到的行和c列。 它們從 1 開始,默認在左上角,因此您可以使用"\\033[1;1H"或僅使用"\\033[H"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM