Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Escape Character's unusal behavior

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading