Search code examples
ckernighan-and-ritchie

KR - visualize backspace


I come across this KR exercise 1-10:

Write a program to copy its input to its output, replace each tab by \t, each backspace by \b, and each backslash by \\ .

Here's a very simple solution:

#include <stdio.h>

int main()
{
    int c;
    const char TAB = '\t';
    const char BACKSPACE = '\b';
    const char BACKSLASH = '\\';
    while( EOF != ( c = getchar() ) )
    {
        if( TAB == c )
        {
            printf( "\\t" );
        }
        else if( BACKSPACE == c )
        {
            printf( "\\b" );
        }
        else if( BACKSLASH == c )
        {
            printf( "\\\\" );
        }
        else
        {
            putchar( c );
        }
    }

    return 0;
}

I found the it works ok to visualize Tab and \ (Backslash) but not Backspace. Looks like Backspaces are not remembered by the console? I'm on Ubuntu 14.04.


This seems a similar issue, but not quite sure it's the same.


Solution

  • I assume you run your program in a terminal and then type some input. The terminal is usually in cooked mode, where a backspace would be immediately interpreted as please erase the previous character. The getchar() wouldn't ever return a backspace.

    If you want to test your program for proper handling of backspaces, pipe them in on standard input, this cirumvents the use of a terminal with the associated cooking:

     $ printf 'foo\bbar\n' | ./a.out
     foo\bbar