Exercise 1-10 (Visible escapes - Tab, backspace, backslash)
Chapter_1 Exercise_1-9 | words Exercise_1-11 |
Exercise 1-10 K&R, p. 20
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.
visible.c download
#include <stdio.h> // for getchar(), putchar(), EOF
// replace tab by \t, backspace by \b and backslash by \\
int main()
{
int c;
while((c = getchar()) != EOF)
{
if (c == '\t') {putchar('\\');putchar('t');}
else if (c == '\b') {putchar('\\');putchar('b');}
else if (c == '\\') {putchar('\\');putchar('\\');}
else {putchar(c);}
}
}
/*
gcc visible.c -o visible
./visible // input from keyboard
Hello!
Hello!\t
What's up\?
\tWhat's up\\?
// Ctrl^D in Linux, Ctrl^Z+Enter in Windows (EOF)
./visible < visible.c // input from source file
./visible < visible // input from binary file
*/
Warning: You should be careful when printing the contents of a binary file in the terminal window. Some of the binary code may be interpreted as a command.
Chapter_1 Exercise_1-9 | BACK_TO_TOP | words Exercise_1-11 |
Comments
Post a Comment