Wednesday, 12 January 2011

The C Programming Language (K&R) 01x09—Escape Sequences—Exercise 1-10 (Part I) - Part II

Exercise 1-10 from K&R

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.

Yesterday I wrote some code to solve the problem from K&R listed above. See here. At the time I said I didn’t know of a function that would print a string and that putchar() didn’t handle strings. The later is true and as for a something to handle strings, it came to me later in one of those dah moments: why didn’t I use the printf() function. Indeed. Why not?
 
There’s one less variable and fewer lines of code in this version so it will run faster. That’s not critical when it comes to a user typing in characters. The computer will spend most of the time waiting for the user. It would be critical if the input is a file.

The other code is preferred if you’re not printing out the characters immediately. There could be lots of reasons for that and presumably the code would be part of something bigger.
 
There’s no doubt there’s more than one way to write code to solve a problem.

Sample Code.

I am using Visual C++ 2010 and creating the code as a console application.

// The standard library includes the system function.
#include <cstdlib>

// C++ standard I/O library
#include <cstdio>

// Change tab, backspace and backspace
// escape sequences with: \t, \b, \\
int main()
{
     // Character input variable.
     int c = 0;

     while ((c = getchar()) !=EOF) {
          
           // Replace tab.
           if (c == '\t')
                printf("\\t");
           // Replace backspace.
           // Won't work because of buffer.
           else if (c == '\b')
                printf("\\b");
           // Replace backslash.
           else if (c == '\\')
                printf("\\\\");
           else
                // No changes.
                putchar(c);
     }

     // keep console window open
     system("pause");

     // return some value
     return 0;
} // end main



No comments:

Post a Comment