Why won't this C program pick up escaped backslashes?
-
27-09-2019 - |
Question
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("\\");
.
OTHER TIPS
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("\\");
Use printf("\\\\")
What does the C compiler do when it finds \\
in the source?