I am making a loading type function so what I wanted to do was to halt my program for a few seconds and then resume the execution inside a loop to make it look like a loading process. Looking up on web I found that I can use std::this_thread::sleep_for()
to achieve this (I am doing this on linux). The problem I am facing is that I am unable to make it work with \r
or any other way to overwrite the last outputted percentage as the program freezes as soon as I do it, however it works perfectly with \n
and it's all confusing to understand why it'd work with a newline sequence but not with \r
.
I am posting the sample code below, can someone tell me what am I doing wrong?
#include<iostream>
#include<chrono>
#include<thread>
int main()
{
for (int i = 0; i<= 100; i++)
{
std::cout << "\r" << i;
std::this_thread::sleep_for(std::chrono::seconds(rand()%3));
}
return 0;
}
I am kinda new to this topic and after some digging I found out that I am messing with the threads. But still not sure why this behavior is happening.