0

i was trying to do the execize 1.10 of k&r so this is :

/* 
 * Exercise 1.10
 *
 * 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 tab 
 * and backspaces visible in an unambiguous way.
 *
 */
#include <stdio.h>

int main()
{
    int c;

    while ((c = getchar()) != EOF) {
        if (c == '\t')
            printf("\\t");
        else if (c == '\b')
            printf("\\b");
        else if (c == '\\')
            printf("\\\\");
        else
            printf("%c", c);
    }
}

If i compile this code with gcc -std=c99 1.10.c -o test it doesn't print \b if i use Backspace. Why? And how I could try to get \b pressing Backspace in Linux ?

A guy has said me:

Your program probably doesn't see that backspace. Terminals buffer by line, by default. So does stdin. Well, stdin's buffering is IDB.

Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
user1088530
  • 2,152
  • 1
  • 13
  • 14
  • 1
    That exercise is intended to work on very old UNIX machines. I think that the way terminals work has changed since that time. – Teo Zec May 30 '14 at 15:57
  • 1
    You might need to execute your code on an `ansi` or `vt100` terminal emulation. – alvits May 30 '14 at 16:02

3 Answers3

2
#include <termios.h>
#include <unistd.h>

int mygetch(void)
{


 struct termios oldt,
    newt;
    int ch;
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
    return ch;
}

use getch then get the ASCII for backsapce using it, no need for enter or to clean input buffer and it returns an int. Enjoy

Zach P
  • 1,731
  • 11
  • 16
  • mm to much complicated for one that is at page 16 of K&R ?? anyway thank you , maybe i will understastand your code after a while :) – user1088530 May 31 '14 at 05:28
2

Usually, the console interprets special characters, like backspace or Ctrl-d. You can instruct the console to not do this with stty.

Before you run the program, you can set the tty to ignore backspace mode with

stty erase ''

and restore the console afterwards with

stty sane

This passes the backspace characters Ctrl-h unchanged to the program you're running.


If this doesn't show any difference, then the backspace key may be mapped to DEL instead of Ctrl-h.

In this case you can just start your program and type Ctrl-h everywhere you would have used the backspace key. If you want to catch the backspace key nevertheless, you must also check for DEL, which is ASCII 127

/* ... */
else if (c == '\b' || c == 127)
    printf("\\b");
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
1

Your code doesn't work because it's intended to run on very old UNIX machines. On modern terminals, the backspace character won't be considered.

Teo Zec
  • 383
  • 2
  • 11