K&R C 1-10 reads:
"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 backspace visible in an unambiguous way."
I have the following code and it does not work with the backspace character because the terminal eats the character. It doesn't seem like there's a solution with the material covered in the book so far. What would the solution be?
#include <stdio.h>
main()
{
int c;
while((c = getchar()) != EOF) {
switch (c) {
case '\t':
printf("\\t");
break;
case '\b':
printf("\\b");
break;
case '\\':
printf("\\\\");
break;
default:
putchar(c);
}
}
}
This is because the Operating System is handling terminal IO, and processes the characters from the keyboard before your program gets to see them.
If you are on a Unix/Linux system, you could wrap the execution of your program like this:
$ stty -icanon -echo; ./a.out; stty icanon echo
This will disable the terminal driver from processing the input in some specific ways: icanon enables the handling of of things like backspace processing, while echo causes the characters you type to be printed. Since your program echos the characters itself, you can turn echo off. The only problem with this is that -icanon also stops EOF processing, so you will need to add an extra condition to get out of the loop:
#include <stdio.h>
#define CTRL(x) (x & 0x1f)
main()
{
int c;
while((c = getchar()) != EOF && c != CTRL('d')) {
...
It is also a good idea while testing programs like this to run them in a separate window, so you can kill the entire session quickly and easily if you end up in a strange terminal mode!
Nothing wrong here. If you were to run this program on a file that contained the backspace character, it would properly convert it. For terminal input, the program will not receive the backspace as it is managed by the input routines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With