C语言实现进度条,显示在同一行

效果如下图:

1、第一种 

#include <stdio.h>
#include <unistd.h>  // for usleep function
#include <string.h>

const char *max_bar = "[--------------------] 100%"; 

void printPctBar(int pct) {
    int width = 20;  // Width of the progress bar
    int pos = width * pct / 100;
    
    for (int i = 0; i < strlen(max_bar); i++)
    {
    	printf("\b"); // del old char
    }
    fflush(stdout);
    
    printf("[");
    for (int i = 0; i < width; ++i) {

        if (i < pos) printf("=");
        //else if (i == pos) printf(">");
        else printf("-");

    }

    printf("] %d%%", pct);
    fflush(stdout);
}


int main() {

    for (int i = 0; i <= 100; ++i) {
        printPctBar(i);
        usleep(50000);  // Sleep for 50 milliseconds
    }

    printf("\n");
    return 0;
}

2、第二种

#include <stdio.h>
#include <unistd.h>  // for usleep function
#include <string.h>

//const char *max_bar = "[--------------------] 100%"; 

void printPctBar(int pct) {
    int width = 20;  // Width of the progress bar
    int pos = width * pct / 100;
    
//    for (int i = 0; i < strlen(max_bar); i++)
//    {
//    	printf("\b"); // del old char
//    }
	
	printf("\r");
    fflush(stdout);
    
    printf("[");
    for (int i = 0; i < width; ++i) {

        if (i < pos) printf("=");
        //else if (i == pos) printf(">");
        else printf("-");

    }

    printf("] %d%%", pct);
    fflush(stdout);
}


int main() {

    for (int i = 0; i <= 100; ++i) {
        printPctBar(i);
        usleep(50000);  // Sleep for 50 milliseconds
    }

    printf("\n");
    return 0;
}

3、Python

#!/usr/bin/python3

import time

def printPctBar(pct):
	pos = (50 * pct // 100)
	print("\r[%s%s] %d%%" % ("▓"*pos, " "*(50-pos), pct), end="")
	
	
if __name__ == "__main__":
	for i in range(101):
		printPctBar(i)
		time.sleep(0.05)
	print("")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值