March 17, 2010

getchar()

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:

#include
/* 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. */
main()
{
int c;
while((c=getchar()) != EOF) {
if(c=='\t') {
c = c - '\t';
printf("\\t");
}
if(c=='\\') {
c = c - '\\';
printf("\\\\");
}
if(c=='\b') { //c doesn't like this code
c = c - '\b';
printf("\\b");
}

putchar(c);

}
}