簡體   English   中英

停止退格以擦除某些輸出

[英]Stop backspace form erasing certain output

我正在使用getch()從鍵盤讀取輸入。 但是,如果用戶錯誤輸入了錯誤的數字,他們自然會希望對其進行更正。 按下退格鍵,然后使ch再次等於0,並從輸出中清除錯誤輸入的數字(因此您將無法再看到它)。 我將ASCII 8字符用作退格鍵,因為getch()可處理ASCII數字。 現在可以使用退格鍵,但現在可以擦除整個輸出行,包括“輸入整數:”。 如何在不將用戶輸入放在換行符的情況下使“輸入整數:”部分不可擦除? 例如:

int main(void)
{
    int ch = 0;

    here: printf("Enter an integer:\t");
    ch = getch();
    if(ch == 8) // 8 is ASCII for a backspace
    {
         ch = 0;
         printf("\b \b");
         goto here;
    } 

    // some output

    return 0;
}

我不希望“輸入整數:”並且用戶輸入的數字在輸出中位於2條不同的行上。

保留一個count變量以告知您是否應該刪除。 例如,將計數從0開始,並在每次鍵入實際字符時將其遞增,並在每次成功刪除字符時將其遞減。 當count為0時,則不應允許您刪除它,並且count變量不會發生任何變化。 它應該這樣

int main(void)
{
    int ch = 0;
    int count = 0;
    printf("Enter an integer:\t");
    here: ch = getch();
    if(ch == 8) // 8 is ASCII for a backspace
    {
        if(count > 0)
        {
            ch = 0;
            count--;
            printf("\b \b");
        }
        goto here;
    }
    else
    {
        printf("%c",ch);
        count++;
        goto here;
    }
    //perhaps add an else-if statement here so that
    //when the enter key is pressed, you don't execute 'goto here'

// some output

return 0;
}

另外,我將here的位置更改為ch = getch(); 因為您不希望每個退格鍵重新打印“輸入整數:”

暫無
暫無

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

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