#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.
Run the program and enter Ctrl H .
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
Is there any other way to get the "\b" character in output ?
If you are supplying the input like:
ab backspace cd
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, ie:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.