Use of \r in C++ – Carriage return to escape special characters

Hello, Coders! In this section, we will discuss the escape sequence \r and its uses in C++ through example.

Escape Sequence

The Escape sequences are generally used in C and C++ programming languages. These are the special characters to change or modify the format of the output string. This sequence of characters is not printed along with the output.

These Characters are the combination of “\” (backslash) which is also called an escape character.

Some examples of Escape Characters:

\a ⇾ Alarm, \t ⇾ Tab, \n⇾new line, \r⇾Carriage Return etc.

Use of \r in C++

\r stands for “Carriage Return”. It is one of the escape sequences which is used to add a carriage return to the text. It tells the terminal emulator to move the cursor to the start of the line, not to the next line, like \n. Furthermore, it allows overriding the current line of the terminal.

Example:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!!!\n";
    cout << "Good Morning!!!";
    return 0;
}

Output:

Hello World!!!
Good Morning!!!
#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!!!\r";
    cout << "Good Morning!!!";
    return 0;
}

Output:

Good Morning!!!

In the first example, the first line “Hello World!!!” is printed and the  “\n” escape sequence moves the cursor to the next line and printed the string in the next line.

While In the second example, the “\r” moves the cursor to the leftmost column, as a result only the last line of the program gets printed on the screen.

I hope his section has helped you to understand the escape sequence and the use of \r in C++.

Happy coding!!!

You can also read, How to detect special character in a string in c++

Leave a Reply

Your email address will not be published. Required fields are marked *