I am a beginner of C programming.
I am learning C by "The C programming language second edition"(by Brain W.Kerninghan and Dennis M.Ritchie)
In the book I am stack with the 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 tabs and backspaces visible in an unambiguous way."
I wrote a program like this.
#include<stdio.h>
int main(void) {
int c;
while ((c = getchar()) != EOF) {
if (c == '\t') {
putchar('\\');
putchar('t');
}
if (c == '\b') {
putchar('\\');
putchar('b');
}
if (c == '\\') {
putchar('\\');
putchar('\\');
}
else {
putchar(c);
}
}
}
but this works weirdly. Like below.
C:\C>gcc Replace2.c
C:\C>a
tab is like this
tab\t is\t like\t this
And on the Internet I found the program below.
#include <stdio.h>
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;
}
And this works quite well.
C:\C>gcc Replace2.c
C:\C>a
tab is like this
tab\tis\tlike\tthis
I wonder why these works differenly. Could someone tell me?
The last
elsein your code is attached only to the lastifstatement. So only if the lastifstatement's condition is false (i.e. the input character is not a backslash), it will take theelseroute and print the character. So it pretty much prints everything except the backslash. In particular, it prints the tabs. That's why there are tabs still remaining in your output.The first two
ifstatements in your code are independent of thatelse. If their conditions are not met, the execution just skips their brackets and continues afterwards. If you want to skip the character once a tab or backslash character is detected in the input, you can either convert everyif(except the first one) intoelse if(as Andreas Wenzel suggested), or issue acontinueinstruction right before the closing bracket in each of those blocks afterif, to skip all the remaining code in its body and enter the next round of the loop.