Search code examples
ckernighan-and-ritchie

Why won't this C program pick up escaped backslashes?


I'm doing K&R's 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 an unambiguous way.

I came up with this...

#include <stdio.h>

int main () {

    int c;
    printf("\n"); // For readability

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

        switch (c) {
            case '\t':
                printf("\\t");
                break;
            case '\b':
                printf("\\b");
            case '\\':
                printf("\\");
                break;
            default:
                printf("%c", c);
                break;
        }

    }

}

For some reason, it refuses to touch backslashes. For example, the output from the program when fed a string such as Hello how\ are you? is Hello\thow\ are you? which means it converted the tab OK, but not the backslash.

Am I doing something wrong?


Solution

  • You probably want to printf("\\\\");, instead of just printf("\\");.