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.

We can use if-statements to detect and print escape sequences for the characters in question.

    #include <stdio.h>
    
    main()
    {
        int c;
    
        while ((c = getchar()) != EOF) {
            if (c == '\t')
                printf("\\t");
            if (c == '\b')
                printf("\\b");
            if (c == '\\')
                printf("\\\\");
        }
    }

Now we have to account for all the other characters. We can do this using a series of nested-if-statements that ensure that our character is not one we want to replace, and then print it:

    #include <stdio.h>
    
    main()
    {
        int c;
    
        while ((c = getchar()) != EOF) {
            if (c == '\t')
                printf("\\t");
            if (c == '\b')
                printf("\\b");
            if (c == '\\')
                printf("\\\\");
            if (c != '\t')
                if (c != '\b')
                    if (c != '\\')
                        putchar(c);
        }
    }

Note: you can enter a backspace character in bash or zsh by hitting the key combination Ctrl-V + Ctrl-H.