tags:

views:

70

answers:

4

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? Thanks

Update

Sorry was making dinner, only looked back now. This is not homework. I'm a web dev, trying to expand my horizons. I was told the K&R book is the best book to start with.

+2  A: 

You should be printing the backslash and its escape.

Currently you're just printing the backslash - here you're escaping the second backslash which would otherwise escape the closing double quote:

printf("\\");
BoltClock
+2  A: 

Use printf("\\\\")

zvrba
Hint: Don't post solutions for homework
Aaron Digulla
In this case it's OK even if it's homework - he pasted working code and showed that he made an effort to solve the problem himself.
zvrba
+4  A: 

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

adamk
Hint: Don't post solutions for homework
Aaron Digulla
@Aaron: I only hope that a 15K rep SO user would know to tag a question as homework if it were so.
adamk
This is _not_ a solution for homework. It's one minor detail that we can help with since the OP has done the bulk of the work. Unless the homework is "Why won’t this C program pick up escaped backslashes?" in which case I fear for the IT industry in the future :-) On top of that, the HW tag was added by someone else.
paxdiablo
Ah, yes, I just thought about it, and realised printing 2 `\\` would require me to escape them both. Whoops! – alex 1 hour ago
alex
+2  A: 

What does the C compiler do when it finds \\ in the source?

Aaron Digulla
Hint: don't be vague for non-homework :-) {Just a subtle jab, please don't take offence}.
paxdiablo