Ilknur Mustafa
Ilknur Mustafa

Reputation: 311

how to print on the same line inside function, avoid flush

I want to display a progress bar however putting the printing code inside a separate function seems to invoke an std::flush as each time the progress bar is printing in a new line. This did not happen when the code was used inline The code:

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

void load(int curr, int total) {
    std::cout << "\n[";
    int pos = 50 * curr/total;
    for (int i = 0; i < 50; ++i) {
        if (i < pos) std::cout << "=";
        else if (i == pos) std::cout << ">";
        else std::cout << " ";
    }
    std::cout << "]" << int(float(curr)/(float)total * 100.0) << " %\r";
    std::cout.flush();
}

int main(){
    
    for( int i = 0; i <= 5; i++ ){
        load(i,5);
    }
    std::cout << std::endl;

    return 0;
}

What it does:

[>                                                 ]0 %
[==========>                                       ]20 %
[====================>                             ]40 %
[==============================>                   ]60 %
[========================================>         ]80 %
[==================================================]100 %

What it's supposed to do: print all on the same line

Upvotes: 1

Views: 462

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117288

The first line in your function outputs \n, which is what makes it print on a new line every iteration.

Fix:

#include <iostream>

void load(int curr, int total) {
    std::cout << '[';

    int pos = 50 * curr/total;

    for (int i = 0; i < 50; ++i) {
        if (i < pos) std::cout << '=';
        else if (i == pos) std::cout << '>';
        else std::cout << ' ';
    }
    std::cout << ']' << int(float(curr)/(float)total * 100.0) << " %\r" << std::flush;
}

int main(){

    for( int i = 0; i <= 5; i++ ){
        load(i, 5);
    }
    std::cout << '\n';
}

Upvotes: 1

Related Questions