redi ramaj
redi ramaj

Reputation: 117

How to properly understand the carriage return (a.k.a. \r)?

I have seen this carriage return example online about a loading effect but I am failing to understand it properly. Why does it have to be 2 \rLoading and not one? Can someone explain it to me?

for (int j = 0; j < 3; j++) {
  cout << "\rLoading   \rLoading";
  for (int i = 0; i < 3; i++) {
    cout << ".";
    sleep(300);
  }
}

Upvotes: 4

Views: 143

Answers (2)

Tomas
Tomas

Reputation: 56

The key is that \r will not clear characters which were printed on the screen earlier. So the first \rLoading act as a display eraser.
In fact you can use 10 spaces instead of the Loading , but you must count it accurately, which is not intuitional.
The following is the optimized code, which can be directly compiled and run on an modern x86 & linux machine. You can try to delete one of the \rLoading and see what will happen for easily understanding.

#include <iostream>
#include <unistd.h>

int main(int argc, char* argv[]) {
  for (int j = 0; j < 3; j++) {
    std::cout << "\rLoading   \rLoading" << std::flush;
 // std::cout << "\r          \rLoading" << std::flush; // same effect
    for (int i = 0; i < 3; i++) {
      std::cout << "." << std::flush;
      sleep(1);
    }
  }
  std::cout << std::endl;
  return 0;
}

Two promotions:

  • a std::flush is needed or you will not see the effects
  • 300 seconds is too long -> 1 seconds

Upvotes: 1

Ctx
Ctx

Reputation: 18410

The first section

\rLoading____

is printed to have the string "Loading" and three empty spaces at the beginning of the line. The next carriage return then sets the cursor to the beginning of the line. Then

Loading

is printed again, but the cursor is now directly behind the word, at the first of the three spaces. Now here:

for (int i = 0; i < 3; i++) {
  cout << ".";
  sleep(300);
}

three dots are printed in an interval of 300 seconds each into the places, where the three dots are.

This whole procedure is iterated three times, so the main purpose of the three blanks of the first "Loading" is, to delete the dots from the previous iteration.

Upvotes: 6

Related Questions