cvisual-studiogetcharputchar

How can I generate an BACKSPACE in a visual studio debug console?


I'm writing a Windows console mode C program using Visual Studio 2019 community. I want each backspace seen in the input stream to be printed as the literal string "\b" in the output.

How do you capture a backspace signal to the console? If I press CTRL-H it deletes the preceding character but I in fact what to getchar() to take the corresponding value.

while ((c = getchar()) != EOF) {
    if (c == '\t') {
        printf("\\t");
    }
    else if (c == '\b')
        printf("\\b");
    else if (c == '\\') {
        printf("\\\\");
    }
    else
        putchar(c);

Solution

  • Windows console performs line edit processing on standard input allowing you to use backspace, delete, left/right cursor and insert/overwrite mode. These characters and key presses do not result in a character being inserted into the input stream.

    You can switch off the input processing using the Win API SetConsoleMode(). For example below I have switched of the processing and line-input mode so that getchar() returns after each character is entered:

    #include <stdio.h>   
    #include <windows.h>
    
    int main()
    {
        HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE); 
        DWORD console_mode = 0 ;
        if( GetConsoleMode( stdin_handle, &console_mode) )
        { 
            console_mode = console_mode & ~(ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT) ;
            SetConsoleMode( stdin_handle, console_mode ) ;
        }
    
        int c = 0 ;
        while( (c = getchar()) != EOF )
        {     
            switch( c )
            {
                case '\t' : printf( "\\t" ); break ;
                case '\b' : printf( "\\b" ); break ;
                case '\\' : printf( "\\\\" ); break ;
                case '\r' : putchar( '\n' ); break ; // Translate ENTER into Newline
                default : putchar( c ); break ;
            }
        }
    }
    

    However it has probably undesirable side-effects such as causing ENTER to be interpreted as \r and for getchar() not to return when ENTER is pressed until after the next character is input. No doubt there is a resolution for that, but I'll leave that for you to experiment. It may be a conflict between what stdin processing and Windows console processing - and perhaps using ReadConsole() and Win API console I/O functions in general would help?