mardi 12 janvier 2021

Can somebody explain the difference in output when using if v/s else if for replacing tabs (\t) using C? K&R Exercise 1-10

I am on windows and using Visual Studio Code.

Question: Write a program to copy its input to its output, replacing each tab with \t, backspace with \b, and backslash with \\.

#include <stdio.h>
void main(){
    int c;
    for(c = getchar(); c != EOF ;)
    {
        if(c == '\t')
        {
            putchar('\\');
            putchar('t');
        }
        if(c == '\\')
        {
            putchar('\\');
            putchar('\\');
        }
        if(c == '\b'){
            putchar('\\');
            putchar('b');
        }
        if(c == ' '){
            putchar('\0');
        }      
        else
        {
            putchar(c);
        }
        
        c = getchar();
    }
}

For the input: This is sparta

I get the output: This\t is\t sparta

I thought this was because, tab is 4 spaces and replacing it with '\t' meant the remaining 3 spaces get converted to blank space. That's why I added the if(c == ' '){putchar('\0'); } condition.

But, I still get an incorrect output.

If, I instead use else if, for the two subsequent conditions for '\\' and '\b', I end up with the correct output : This\tis\tsparta. Why does this happen?

Aucun commentaire:

Enregistrer un commentaire