"The C Programming Language", 2nd edition, Kernighan and Ritchie

Answer to Exercise 1-10, page 20

Category 0 Solution by Gregory Pietsch Category 1 Solution by Richard Heathfield

Write a program to copy its input to its output, replacing each tab by \t , each backspace by \b , and each backslash by \\ . This makes tabs and backspaces visible in an unambiguous way.



Category 0
Gregory Pietsch pointed out that my solution was actually Category 1. He was quite right. Better still, he was kind enough to submit a Category 0 solution himself. Here it is:

/* Gregory Pietsch <gkp1@flash.net> */

/*
 * Here's my attempt at a Category 0 version of 1-10.
 *
 * Gregory Pietsch
 */

#include <stdio.h>

int main()
{
    int c, d;

    while ( (c=getchar()) != EOF) {
        d = 0;
        if (c == '\\') {
            putchar('\\');
            putchar('\\');
            d = 1;
        }
        if (c == '\t') {
            putchar('\\');
            putchar('t');
            d = 1;
        }
        if (c == '\b') {
            putchar('\\');
            putchar('b');
            d = 1;
        }
        if (d == 0)
            putchar(c);        
    }
    return 0;
}





Category 1


This solution, which I wrote myself, is the sadly discredited Cat 0 answer which has found a new lease of life in Category 1.

#include <stdio.h>

#define ESC_CHAR '\\'

int main(void)
{
  int c;

  while((c = getchar()) != EOF)
  {
    switch(c)
    {
      case '\b':
        /* The OS on which I tested this (NT) intercepts \b characters. */
        putchar(ESC_CHAR);
        putchar('b');
        break;
      case '\t':
        putchar(ESC_CHAR);
        putchar('t');
        break;
      case ESC_CHAR:
        putchar(ESC_CHAR);
        putchar(ESC_CHAR);
        break;
      default:
        putchar(c);
        break;
    }
  }
  return 0;
}




Back to index





You are visitor number - call again soon!