Understand backspace (\b) behaviour in C
Asked Answered
S

2

10

This program copy its input to its output, replacing TAB(\t) by \t backspace(\b) by \b. But here in my code I am unable to read input character when I enter backspace its not replacing as a tab works .

Compiling with GCC in Linux:

#include<stdio.h>
int main(void)
{
    int c=0;
    while((c=getchar())!=EOF){
     if(c=='\t'){
      printf("\\t");
     if(c=='\b')
      printf("\\b");
    }
    else
     putchar(c); 
}
return 0;
}

Suppose if I type vinay (tab) hunachyal

Output:vinay\thunachyal 

If I type vinay(and 1 backspace)

Output:vina

So my query is why vina\b is not printing in this case?
Is it possible to detect \b and print \b? if not whats the reason

Note: I need at run time input backspace not providing separate file having \b

Sprague answered 4/9, 2013 at 8:44 Comment(0)
W
8

The backspace is consumed by the shell interpreter, so your program will never see it, also your code is (slightly) broken, due to misplaced braces, not helped by the poor indentation.

Here is a corrected version:

#include<stdio.h>
int main(void)
{
    int c=0;
    while((c=getchar())!=EOF){
        if(c=='\t')
            printf("\\t");
        else if(c=='\b')
            printf("\\b");
        else
            putchar(c);
    }
    putchar('\n');
    return 0;
}

which works as expected:

$ echo 'vinay\thunachyal\b' | ./escape
vinay\thunachyal\b
Watkin answered 4/9, 2013 at 8:46 Comment(3)
Is there any way to avoid backspace eaten by shell without generating separate file, i need at the run time of backspace keySprague
even my code also work If i echo 'vinay\thunachyal\b' | ./a.out, but my query is there any way to detect backspace at d run time of program as tab is working @runtime like that backspace, correct me if im wrong.Sprague
@vinayhunachyal Yes, your program is doing that. The issue here is simply how you get the backspace to the program. Using echo, as above seems a simple approach.Watkin
V
4

If I haven't misinterpreted the question, you may use 'Ctrl-H' to send a backspace. Using trojanfoe's corrected code, when you type:

vinay^H

It will print:

vinay\b

^H means 'Ctrl-H', it's ASCII character #8, which is backspace.

Variorum answered 15/5, 2014 at 6:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.