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;
}
'The C Programming Language' 카테고리의 다른 글
Chapter 1 - A Tutorial Introduction 12 (0) | 2009.03.25 |
---|---|
Chapter 1 - A Tutorial Introduction 11 (0) | 2009.03.25 |
Chapter 1 - A Tutorial Introduction 9 (0) | 2009.03.25 |
Chapter 1 - A Tutorial Introduction 8 (0) | 2009.03.25 |
Chapter 1 - A Tutorial Introduction 7 (0) | 2009.03.25 |