The C Programming Language, Ch.1 Exercise 1.10 (Getchar and Putchar)

Your main problem is that you are outputting the character regardless of the fact that you may have already output its translation. Those if statements will do what you expect but, in their present form, they simply drop through to the next statement.

Hence you'd be looking for something more like this:

while ((c = getchar()) != EOF) {
    // Detect/translate special characters.

    if (c == '\t') {
        putchar ('\\');
        putchar ('t');
        continue;              // Go get next character.
    }

    if (c == '\b') {
        putchar ('\\');
        putchar ('b');
        continue;              // Go get next character.
    }

    if (c == '\\') {
        putchar ('\\');
        putchar ('\\');
        continue;              // Go get next character.
    }

    // Non-special, just echo it.

    putchar (c);
}

Another possibility, shorter and more succinct would be:

while ((c = getchar()) != EOF) {
    // Detect/translate special characters, otherwise output as is.

    switch (c) {
        case '\t': putchar ('\\'); putchar ('t');  break;
        case '\b': putchar ('\\'); putchar ('b');  break;
        case '\\': putchar ('\\'); putchar ('\\'); break;
        default:   putchar (c);
    }
}

I know im late to the party, but this question pops up in chapter one before else, case, continue, and functions are introduced.

Here is a working solution to exercise 1-10 that involves only concepts introduced up to the point of the exercise. You need to keep track of whether an escaped character was found and then display the copied character only if one was not found.

#include <stdio.h>

int main() {

  int input;

  while((input = getchar()) != EOF){

    int escaped = 0;

    if(input == '\t'){
        putchar('\\');
        putchar('t');
        escaped = 1;
    }

    if(input == '\b'){
        putchar('\\');
        putchar('b');
        escaped = 1;
    }

    if(input == '\\'){
        putchar('\\');
        putchar('\\');
        escaped = 1;
    }

    if(escaped == 0){
      putchar(input);
    }
  }
}

Tags:

C

Putchar

Getchar