簡體   English   中英

從std :: cout刪除最后一個值

[英]erasing the last value from the std::cout

我正在為兩個玩家創建一個猜謎游戲。 首先,我希望用戶輸入一個旨在保密的數字。 為了保密,我想刪除用戶最后輸入的任何內容。 我正在嘗試向后移動光標,並在用戶輸入數字的地方插入空格。 我現在嘗試使用cout << "\\b" << "\\b" << "\\b" << " " ,您可以在下面的循環中看到它。

到目前為止,這是我的代碼:

do{ //initial do-while loop to begin game

    int secretNumber = 0; //initilized to a default value of 0 to make the compiler happy

    do {
        //prompt user for input
        cout << "Please choose a secret number between 1 and 10: ";
        //read in user input
        cin >> secretNumber; //store user input in variable
        cout << "\b" << "\b" << "\b" << " "; //<------- this is my attempt to clear the user input
        if(secretNumber <= 0 || secretNumber > 10){
            cout << "You have attempted to enter a number outside of the acceptable range." << endl;
        }   
    }while ((secretNumber <= 0 || secretNumber > 10)); //repeat do-while loop if user input is out of range

當前,它僅打印另一行,並以空格作為第一個字符,而不是返回到前一行並將用戶輸入的整數替換為“”。

請不要給我任何操作系統特定的解決方案,我需要在Windows和Linux上進行編譯。

如果終端仿真器(或Windows上使用的命令外殼)支持基本的ANSI控制字符,則可以輸出一個反向換行序列,然后是一個終止行序列。 反向換行是必需的,因為用戶將鍵入回車鍵以終止輸入,因此光標不再在同一行上。 這些代碼分別是"\\033[F""\\033[K" 但是不能保證這將起作用。

從歷史上看,您可以使用現在退出的Posix接口getpass讀取行而不回顯。 我不相信這是Windows實現的,盡管它仍然是glibc一部分,但不鼓勵使用它。 不幸的是,沒有標准的替代品。

在Posix系統中,可以使用termios工具來實現與控制台無關的終端控制。 基本上,您只需要關閉ECHO標志即可。 (有關更多詳細信息,請參見man termios 。)在Windows上,有一個類似的界面。 但是,使用這些接口很容易遇到麻煩,因為即使用戶使用 ctl-C終止程序 (或使用ctl-Z暫停程序),也需要重新啟用回顯。 正確地做到這一點非常棘手,而您在互聯網上找不到的幼稚解決方案通常不會。

話雖如此,請參見在不使用getpass(3)的情況下在C中獲取密碼? 對於一些可能的解決方案。

暫無
暫無

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

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