如何在函数内部的同一行上打印,避免刷新

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

我想显示一个进度条,但是将打印代码放在一个单独的函数中似乎会调用 std::flush,因为每次进度条都在新行中打印。内联使用代码时不会发生这种情况 代码:

#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;
}

它的作用:

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

它应该做什么:在同一行打印所有内容

函数的第一行输出 \n,这就是它每次迭代都在新行打印的原因。

修复:

#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';
}