繁体   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