0

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.

  • "_ Also, I noticed incoherent number of spaces ..._" The "horizontal tab" means "advance the cursor to the next column that is evenly divisible by (in your case) 8." In other words, to col 8, 16, 24, 32,... Maybe read the Wikipedia page for "tab stops". – Fe2O3 Apr 01 '23 at 08:48
  • And the backslash is misinterpreted, it must be replaced by 2 backslashes not one. – dalfaB Apr 01 '23 at 15:10

1 Answers1

2

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;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621