Hello...

I'm learning C with "The C Programming Language" book, and I'm stuck at
exercise 1-10 which asks to:

"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."

Here is my code:

#include <stdio.h>

/* copy input to output, replacing each tab by \t,
   each backspace by \b, and each backslash by \\ */
main()
{
    int c;
    int back;
    while ((c = getchar()) != EOF) {
        if (c == '\t') {
            putchar('\\');
            putchar('t');
        }
        if (c == '\b') {
            putchar('\\');
            putchar('b');
        }
        if (c == '\\') {
            putchar('\\');
            putchar('\\');
        }
        if (c != '\t')
            if (c != '\b')
                if (c != '\\')
                    putchar(c);
    }
}

Everything is working fine, except that it won't print "\b" when the user presses
the backspace key. Could anyone give me a hint on how to solve this?

Recommended Answers

All 7 Replies

It is (almost) beyond the programmatic control. The backspace character is processed by the console driver and not delivered to the program. You may prepare the file with embedded backspaces and redirect input from it; this way the driver is bypassed, and you will see the "\b".

@nezachem
can you explain complete procedure for that printing \b

Open a new file in a good editor. Type some text, embedding backspaces in it. How to embed a backspace depends on the editor. In vim, type Ctrl-V Ctrl-H (in linux) or Ctrl-Q Ctrl-H (in windows). You will see ^H, this is a backspace. Save the file as foo. Then type your_program < foo .

One way is to check the ASCII value of each character. The space character, / character all have distinct values

Yes, you can use a call to getch() or getche() and check for the ASCII values.

By the way, is the function of the backspace key on windows the same as on UNIX?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.