4

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.

Community
  • 1
  • 1
artm
  • 17,291
  • 6
  • 38
  • 54

1 Answers1

4

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
Jens
  • 69,818
  • 15
  • 125
  • 179
  • Yeah I tested it over terminal, and indeed backspace was never stored. Btw, any reading recommendation for the `cooked mode` terminal? – artm Sep 02 '15 at 23:05
  • @artm What constitutes cooked mode (and all other terminal settings) is usually found in the `stty(1)` manual page. – Jens Sep 03 '15 at 10:13