Escape Character's unusal behavior

Advertisements

I’m getting an unintended output from this code.


int main() {


    int var;
    

    while ((var = getchar() ) != '\n') {
        if (var == '\t')
            printf("\\t");
        if (var == '\b')
            printf("\\b");
        if (var == '\\')
            printf("\\");

        putchar(var);       }
    
    putchar('\n');
}

When I pass in the following input, I get the output like:

Input:Hello   World
Output:Hello\t World

As of my understanding, the output should’ve been, Hello\tWorld. Also, for inputs:

Input:HelloW  orld
Output:HelloW\t      orld

Input:Hello\World
Output:Hello\\World

Wasn’t the result supposed to be, Hello\World and why is there certain spaces? Is this a compiler issue? I’m using, gcc (Debian 10.2.1-6) 10.2.1 20210110
Also, I noticed incoherent number of spaces left by my terminal when I press tab successively. Example: 3 spacing gap when pressed 1st time, 8 spacing gap when pressed the 2nd time. Though, I don’t think it has anything to do with this.

>Solution :

The problem is that you always print the character you read, even if it’s an escape character.

So if you input a tab then you print \t followed by the actual tab.

Either change to an if .. else if ... else chain, or use a switch statement:

switch (var)
{
case '\t':
    printf("\\t");
    break;

// Same for the other special characters...

default:
    // Any other character
    if (isprint(var))
        putchar(var);
    break;
}

Leave a ReplyCancel reply