-4
int main()    
{
   int c, d;
   while ( ( c = getchar() ) !=  EOF )
   {
      d = 0;
      if (c == '\b')
      {
          putchar('\\');    
          putchar('b');
          d = 1;
      }
      if (d == 0)
          putchar(c);
   }  
   return 0;
}

But when i press backspace \b is not being displayed in place of that

Arun A S
  • 6,421
  • 4
  • 29
  • 43
Vibha
  • 1
  • What platform are you using? – Politank-Z Apr 14 '15 at 16:17
  • `getch()` instead of `getchar()` – BLUEPIXY Apr 14 '15 at 16:28
  • 2
    The code would be much simpler with the d variable removed entirely and just use "else" instead of "if (d == 0)" – Brad Budlong Apr 14 '15 at 17:26
  • 1
    possible duplicate of [Understand backspace (\b) behaviour in C](http://stackoverflow.com/questions/18609213/understand-backspace-b-behaviour-in-c) – gnat Apr 14 '15 at 17:37
  • 2
    possible duplicate of [What does getchar() exactly do?](http://stackoverflow.com/questions/3676796/what-does-getchar-exactly-do) -- getchar() uses buffered input, your program never receives a backspace from the terminal in the first place. – Matthew Read Apr 14 '15 at 17:37
  • 1
    BTW there is no need to use the extra variable d, you can just replace the `if (d==0)` with an `else`. – Bjorn Munch Apr 14 '15 at 17:59

1 Answers1

0

But when i press backspace \b is not being displayed in place of that

Your code compiles just fine, however backspace won't be printed to the console. Unlike the other format characters, backspace won't show up.

The reason is, as mentioned above:

getchar()

Places your input into the buffer, reads, then outputs the text once you press enter. Logically, the backspace character won't be printed as a result, unlike tabs or spaces.

getch()

getch() will output backspace; it does not read from the standard input, and instead returns input without waiting for you to press enter. getch() is also a part of the conio.h header file.

#include <stdio.h>
#include <conio.h>

int main()
{
 int c, d;
 while ((c = _getch()) != EOF)
 {
        if (c == '\b')
        {
             printf("\\b");
             printf("\nValue of backspace: %d \n", c);
        }
        else
             putchar(c);
 }
 return 0;
}

Similar program that will output the value of backspace and will print backspace to the screen when entered.

int d

Didn't really need it to run the program, you could use "else" instead of:

if(d == 0)

I hope this answer helps you in some way.

KinoR
  • 46
  • 5