satoru kurita
satoru kurita

Reputation: 101

What is the difference between these loops?

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?

Upvotes: 0

Views: 79

Answers (1)

AlojzyBąbel
AlojzyBąbel

Reputation: 1

The last else in your code is attached only to the last if statement. So only if the last if statement's condition is false (i.e. the input character is not a backslash), it will take the else route 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 if statements in your code are independent of that else. 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 every if (except the first one) into else if (as Andreas Wenzel suggested), or issue a continue instruction right before the closing bracket in each of those blocks after if, to skip all the remaining code in its body and enter the next round of the loop.

Upvotes: 0

Related Questions