Frage

#include <stdio.h>
/* replacing tabs and backspaces with visible characters */
int main()
{
  int c;
  while ( (c = getchar() ) != EOF) {
       if ( c == '\t')
          printf("\\t");
       else if ( c == '\b')
          printf("\\b");
       else if ( c == '\\')
          printf("\\\\");
       else 
          putchar(c);
    }

   return 0;
  }

Now my question is .. Why can't I see "\b" in the output ? I have written this code in Ubuntu terminal. Is there any other way to get the "\b" character in output ? If there is , please explain in simple words as I have just started learning C programming.This example is from K&R exercise 1-10.

War es hilfreich?

Lösung

Run the program and enter CtrlH.

The key-code send by the backspace key (also: <---) is most probably eaten by the shell. This depends on how the terminal is configured. Read here for details: http://www.tldp.org/HOWTO/Keyboard-and-Console-HOWTO-5.html

Andere Tipps

Is there any other way to get the "\b" character in output ?

If you are supplying the input like:

abbackspacecd

to your program then it'd result in abc because that is what the shell passed to the program.

Ensure that you send the correct input to the program. Invoke it by saying:

printf $'ab\bcd' | /path/to/executable

and it'd print the expected output, i.e.:

ab\bcd

This is not valid C code. It should look like this:

#include <stdio.h>
/* replacing tabs and backspaces with visible characters */
int main()
{
  int c;
  while ( (c = getchar() ) != EOF) {
       if ( c == '\t')
          printf("\\t");
       else if ( c == '\b')
          printf("\\b");
       else if ( c == '\\')
          printf("\\\\");
       else 
          putchar(c);
   } // <-- note the closing curly brace
   return 0;
}

You should prepare a file containing the \b (0x08) and use it as input for your program. Another way would be to press Ctrl-H and then Enter (Thanks @alk for the key combination)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top