Hello,
I am learning C through the book
"The C Programming Language", 2nd edition, Kernighan and Ritchie
I am on exercise, 1-10. I did not understand the below answer in this exercise.
Question:
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.
Answer:
Why do you use two putchar statements:
for example :
putchar('\\');
putchar('t');
why do you need putchar( ' \\ ') ? What does it do ?
also what is the purpose of variable d ?
Also, Is there another way to write this code ?
Thanks,
Tolga
I am learning C through the book
"The C Programming Language", 2nd edition, Kernighan and Ritchie
I am on exercise, 1-10. I did not understand the below answer in this exercise.
Question:
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.
Answer:
Code:
int main()
{
int c, d;
while ( (c=getchar()) != EOF) {
d = 0;
if (c == '\\') {
putchar('\\');
putchar('\\');
d = 1;
}
if (c == '\t') {
putchar('\\');
putchar('t');
d = 1;
}
if (c == '\b') {
putchar('\\');
putchar('b');
d = 1;
}
if (d == 0)
putchar(c);
}
return 0;
}
for example :
putchar('\\');
putchar('t');
why do you need putchar( ' \\ ') ? What does it do ?
also what is the purpose of variable d ?
Also, Is there another way to write this code ?
Thanks,
Tolga
Last edited by a moderator: