简体   繁体   中英

Stop backspace form erasing certain output

I am using getch() to read input from the keyboard. 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). I used the ASCII 8 character for a backspace as getch() works with ASCII numbers. 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.

Keep a count variable to tell whether or not you should delete. 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. When count is 0, then you shouldn't be allowed to delete and nothing happens to the count variable. 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(); because you don't want each backspace to reprint "Enter an integer:"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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