0

I am trying to print escape sequences in this program:

/*print escape sequences*/

#include <stdio.h>

int main()
{
int esc;
printf("Hit any escape sequence:");
esc=getchar();
//scanf("%d",&esc);
switch(esc){
    case '\t':
        printf("tab");
        break;
    case '\n':
        printf("newline");
        break;
    case '\b':
        printf("backspace");
        break;
    }
printf("\n");
return 0;
}

The thing is I tried doing this with scanf and it never printed anything.

Then I tried with getchar and it prints tab and newline. But backspace I couldn't get it to print backspaces.

How to print backspace?

Ani Menon
  • 27,209
  • 16
  • 105
  • 126
mrigendra
  • 1,472
  • 3
  • 19
  • 33
  • How scanf("%d",&esc); is wrong? – mrigendra May 02 '16 at 05:48
  • Also the linked answer says that backspace = Ctrl+H. It says backspace is taken by interpreter than how it worked for newline? – mrigendra May 02 '16 at 05:56
  • `"%d"` format specifier is used to read `char` and not `int`. – Mohit Jain May 02 '16 at 06:33
  • Ok so I can send int values to get detected as escape sequence, and that works well with backspace too. If I make 'esc' as char it won't print backspace – mrigendra May 02 '16 at 06:35
  • I didn't say making `esc` a `char` is the solution. I said with `int`, it won't work even for other escape sequences. – Mohit Jain May 02 '16 at 06:37
  • I think that making esc as int is a solution. Making it char makes it hard to detect other escape sequences as 'enter' also comes into picture. Isn't it? – mrigendra May 02 '16 at 06:43
  • Always remember `"%d"` reads an integer that begins with a non-zero digit. – Mohit Jain May 02 '16 at 06:56
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/110801/discussion-between-mrigendra-and-mohit-jain). – mrigendra May 02 '16 at 08:12

0 Answers0