Search code examples
c++escaping

Why do I get this output when I use escape sequence?


I try to study escape sequence so I am testing \n, \r, \t and I thought \r makes the cursor move to the beginning of the line.

I want to print:

hello
\r wokring      \t working \n working

so I enter this code in visual studio 2022

#include <iostream>

int main(void)
{
    std::cout << "hello \n \\n working \r \\r working \t \\t working" << std::endl;

    return 0;
}

but it prints:

hello
\r_working       \t working

and a web compiler prints:

hello 
 \n working \r working   \t working

Why does this happen? Is there something I mistake about this?


Solution

    • \r is the carriage return (aka CR).
    • \n is the new line character (aka LF / Line feed).
    • Both characters are most often combined on Windows as \r\n (aka CRLF, that you can find e.g. in VBA through the vbCRLF constant).

    That has historically always been a little bit of a mess as explained there.

    We can work out your string to figure out what is going on:

    hello \n \\n working \r \\r working \t \\t working
    
    1. Hello is written, then it goes to the next line.
    2. \n working is written, then it goes back to the start of the line.
    3. \r working, then a tab, then \t working is written, but all of that overwrites \n working (since the cursor went back to the start of the same line).

    I suspect your web compiler does not run on Windows (probably some Linux distribution), hence the different result.