Welcome to the Linux Foundation Forum!


Hi, i have a c question. My program is supposed to replace all the backspace char (hitting backspace) with \b, the tab char with \t the \ (slash) char with \\

my problem is everything works in my program except for printing backspace.

for example:

Input: asdf1234(hit tab)12(hit backspace)34( hit \ char )

Output: asdf1234\t134\\

as you can see \t and \\ are used in place of tab and \

but backspace merely deletes a char instead of just printing \b

i heard somewhere that the terminal reads and deals with backspaces before the program, could this be the reason getchar() cannot get a value when backspace is hit? I don't know if its true or not. The following code is what i wrote in responce to an exersice in k&r second edition.

heres the code:


/* 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. */



int c;

while((c=getchar()) != EOF) {

if(c=='\t') {

c = c - '\t';



if(c=='\\') {

c = c - '\\';



if(c=='\b') { //c doesn't like this code

c = c - '\b';







  • heres the source code in a text file [file name=replacetab.txt size=489]http://www.linux.com/media/kunena/attachments/legacy/files/replacetab.txt[/file]
  • woboyle
    woboyle Posts: 501
    On most systems, the backspace is ^H; however, if your terminal is configured for buffered input, the driver will intercept the ^H and do the "rubout the last character input" that you have experienced. You need to modify the behavior of the tty with either the stty command before you start your program, or within your program with the tcsetattr() function. You can turn off buffered input so that you can directly intercept the back-space that you input from the keyboard.
  • Thanks for your reply. Yeah I kind of figured something like that, im glad I gave up on the excise or else I would still be trying it. So thanks, I guess I just wont mess with it.
  • woboyle
    woboyle Posts: 501
    You can use the stty command from the shell to alter this behavior before you start your program.
    stty erase 0 ; myprogram ; stty ek
    This will turn off the backspace/erase actions, run your program, and then turn it back on. You can do the same thing with other special characters as well.


Upcoming Training