分页: 1 / 1

用C写了个进度条函数,结果光标跳来跳去的

发表于 : 2014-10-14 14:33
rikhtdss

代码: 全选

#include <stdio.h>
#include <unistd.h>

/* 打印进度条 */
void DisplayProgress(long current, long total) {
    int width = 50; /* 进度条宽度为 50 个字符 */
    int i;
    /* 清空行 */
    for (i = 0; i < width + 7; i++) {
        putchar('\b');
    }
    
    int LoopTimes = (int)((double)current / total * width);

    putchar('[');
    for (i = 0; i < LoopTimes; i++)
        putchar('#');
    for (i = 0; i < width - LoopTimes; i++)
        putchar('-');
    printf("] ");
    printf("%3.0f%%", (double)current / total * 100);    
}

int main(void)
{
    int start = 1, end = 285;
    int i;
    for (i = start; i <= end; i++) {
        DisplayProgress(i, end);
        usleep(100000);
    }
    printf(" Done!\n");
    return 0;
}

怎么在函数完成一轮输出后将光标移到行尾?

Re: 用C写了个进度条函数,结果光标跳来跳去的

发表于 : 2014-10-14 14:44
__slucx__
函数DisplayProgress结尾加fflush(stdout);

Re: 用C写了个进度条函数,结果光标跳来跳去的

发表于 : 2014-10-14 15:00
rikhtdss
解决了,谢谢楼上!

Re: 用C写了个进度条函数,结果光标跳来跳去的

发表于 : 2014-12-31 16:42
往事remember
我想问一下楼主,把你的程序跑起来之后,为什么后面会出现很多%号