#Exercise 1-10

38 messages · Page 1 of 1 (latest)

junior holly
#

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.

I am not getting how do I test for backspace and I am not sure if I am doing it correctly, please review and give me some feedbacks.

#include <stdio.h>

main() {
  int c;

  while ((c = getchar()) != EOF) {
    if (c == '\t') {
      putchar(92);
      putchar(116);
    } else if (c == '\b') {
      putchar(92);
      putchar(98);
    } else if (c == '\\') {
      putchar(92);
      putchar(92);
    } else {
      putchar(c);
    }

  };
}
final basin
#

The backspace character is '\b' as clearly written there, you just compare normally.

junior holly
#

yes that part I am clear about it but how do I test while running this application?
if I hit backspace button will it generate \b?

iron moth
#

oh I think I get it
your terminal is line-buffered, so the backspaces aren't actually making it to stdin
is that right?

junior holly
#

yes

iron moth
#

bingo

#

which os are you on?

junior holly
#

what can I do?

#

arch

iron moth
#

nice

junior holly
#

using kitty

iron moth
#

gimme 2 seconds

junior holly
#

whats nice about it hehe?

#

okay

junior holly
#

I am only at the first chapter and not sure which library or function to do I use to read the file.

final basin
#

You can pipe the file on the command-line.

iron moth
#

how on god's green earth do you write a backspace to a file

junior holly
#

will that work as reading the character from stdin?

final basin
#

Yes.

junior holly
#

hehe

final basin
#

The file then is the stdin.

final basin
iron moth
#

good to know

junior holly
#

whats that

final basin
#

What specifically?

iron moth
#

I swear there's a way to turn off line buffering in the terminal tho
using bash set or something
or was it ansi escapes?

junior holly
#

so you use control+V V right?

final basin
#

Ctrl+V then Ctrl+H.

junior holly
#

ok will try it thanks

iron moth
#

oh printf does work (go figure)

printf '\b' | ./your-program
#

(run in your terminal)

junior holly
#

nice

#

so okay so thats workings thanks guys and what about the logic is putchar(92); putting asci only the way to do this?

#

is there any better way to do this?

final basin
#

'\\'.

iron moth
#

characters are just integers:

  • characters in C (char) are an integral type (it's better to think of them as "bytes" than "characters")
  • character constants in C are integers, confusingly (yes, I mean int, not char)