Jul 27, 2014

K&R Exercise 1.10 Making tabs and backspaces visible in unambiguous way

Problem Statement

Exercise 1-10: 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 unambiguous way.


Solution

Strategy
  • Input will done via getchar() till EOF in a loop.
  • Each character will assigned to variable c.
  • c will be compared to '\t'; replacing it with '\\' and 't'
  • c will be compared to ' '; replacing it with '\\' and 'b'
  • c will be compared to '\\'; replacing it with '\\' and '\\'

The solution would look as follows.


#include <stdio.h>
int main()
{
   int c;
   while((c = getchar()) != EOF) {
      if(c == '\t') {
         putchar('\\');
         putchar('t');
      }else if(c == ' ') {
         putchar('\\');
         putchar('b');
      }else if(c == '\\') {
         putchar('\\');
         putchar('\\');
      }else {
         putchar(c);
      }
   }
   return 0;
}

Output looks as follows.


$ ./e_1_10.out 
This    is very long line\
This\tis\bvery\blong\tline\\

Links

Next Article - K&R : Exercise 1.11 - Testing word count
Previous Article - K&R Exercise 1.9 Replace multiple blank with single blank

All Article - K & R Answers

No comments :

Post a Comment