loading function more efficiency and other minor issues

I created this fake loading function just so my program looks more cool to the examiner but the thing is i want the previous loading to disappear.

for example i want the loading 10% to appear then loading 20% comes in place of loading 10% and loading 10% disappears and then loading 30% comes and so on.

Also please suggest an efficient method such that i dont have to write std::this_thread thing again and again after each line.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void loading()
{
               for(int i=0;i<5;i++)
        {
                cout<<"Loading 10%"<<endl;
                std::this_thread::sleep_for(std::chrono::seconds(2));
                cout<<"Loading 30%"<<endl;
                std::this_thread::sleep_for(std::chrono::seconds(2));
                cout<<"Loading 60%"<<endl;
                std::this_thread::sleep_for(std::chrono::seconds(2));
                cout<<"Loading 90%"<<endl;
                std::this_thread::sleep_for(std::chrono::seconds(2));
                cout<<"Loading 100%"<<endl;
                std::this_thread::sleep_for(std::chrono::seconds(2));
        }
}
Unless you clear the screen before each print, I do not believe there is a way to achieve what you are looking for with command line c++. With a gui, you could simply update the label or string that shows the loading message.

Anytime you ask, is there any way to avoid writing xxx again and again, you should start thinking function. In your case, a very simple function like the following

1
2
3
4
5
6
void sleep(int sec)
{
   std::this_thread::sleep_for(std::chrono::seconds(sec));
}

//now you can use sleep(2); 
Last edited on
Try using \r to return the carriage position to the start of the line.
This implies that each line must be the same length or longer than the previous line.
This also assumes the OS supports \r.
1
2
3
4
5
6
7
8
9
10
    cout<<"Loading 10%\r";
    sleep (2);
    cout<<"Loading 30%\r";
    sleep (2); 
    cout<<"Loading 60%\r";
    sleep (2); 
    cout<<"Loading 90%\r";
    sleep (2); 
    cout<<"Loading 100%"<<endl;
    sleep (2);    

Why are you doing this 5 times?

BTW, I absolutely detest programs that insert artificial delays just to look "cool".
Last edited on
Try this; it may work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <thread>
#include <chrono>

void put_pct( int pct, int delay_in_secs = 2 )
{
    std::this_thread::sleep_for( std::chrono::seconds(delay_in_secs) ) ;
    std::cout << "\b\b\b" << pct << '%' << std::flush ;
}

int main()
{
    std::cout << "loading ..." << std::flush ;
    for( int pct : { 10, 30, 60, 90, 100 } ) put_pct(pct) ;
    std::cout << '\n' << std::flush ;
}
Last edited on
>Unless you clear the string before each print

exactly what i need
Oops, I meant the screen I'll edit and adjust. Meanwhile other answers may be worth taking a look at.
Topic archived. No new replies allowed.