简体   繁体   English

停止退格以擦除某些输出

[英]Stop backspace form erasing certain output

I am using getch() to read input from the keyboard. 我正在使用getch()从键盘读取输入。 But if the user enters a wrong number by mistake, they would naturally want to correct it. 但是,如果用户错误输入了错误的数字,他们自然会希望对其进行更正。 Pressing the backspace then makes ch equal to 0 again, and clears the wrongly entered number from the output (so you cannot see it anymore). 按下退格键,然后使ch再次等于0,并从输出中清除错误输入的数字(因此您将无法再看到它)。 I used the ASCII 8 character for a backspace as getch() works with ASCII numbers. 我将ASCII 8字符用作退格键,因为getch()可处理ASCII数字。 The backspace now works, but it can now erase the entire output line, including 'Enter an integer:'. 现在可以使用退格键,但现在可以擦除整个输出行,包括“输入整数:”。 How can I go about making the 'Enter an integer:' part unerasable without putting the user's input on a newline? 如何在不将用户输入放在换行符的情况下使“输入整数:”部分不可擦除? For example: 例如:

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;
}

I don't want "Enter an integer:' and the numbers inputted by the user to be on 2 different lines in the output. 我不希望“输入整数:”并且用户输入的数字在输出中位于2条不同的行上。

Keep a count variable to tell whether or not you should delete. 保留一个count变量以告知您是否应该删除。 For example, start the count at 0, and increment it everytime you type an actual character, and decrement it everytime you successfully delete a character. 例如,将计数从0开始,并在每次键入实际字符时将其递增,并在每次成功删除字符时将其递减。 When count is 0, then you shouldn't be allowed to delete and nothing happens to the count variable. 当count为0时,则不应允许您删除它,并且count变量不会发生任何变化。 It should like this, 它应该这样

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;
}

Also, I changed the location of here to ch = getch(); 另外,我将here的位置更改为ch = getch(); because you don't want each backspace to reprint "Enter an integer:" 因为您不希望每个退格键重新打印“输入整数:”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM