Обновление строки индикатора прогресса с помощью «\ r» в начале пропускает или пропускает итерации - PullRequest
0 голосов
/ 22 декабря 2018

Я хочу написать простую функцию индикатора выполнения на C для дальнейшего использования, но возникла проблема.Обновляя строку индикатора выполнения с помощью "\ r" и печатая ее новое значение, функция пропускает или пропускает итерации.

Я сделал видео , где вы можете видеть, что эта функция правильно вычисляети строит строку для каждой итерации, но когда я добавляю "\ r" в начале строки, она начинает пропускать итерации.

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

void render_progress_bar( int, int, int, char, char );

int main( void ) {
    for ( int i = 1; i <= 60; i++ ) {
            render_progress_bar( i, 60, 50, '#', ' ' );
            usleep( 64000 );
    }

    return EXIT_SUCCESS;
}

void render_progress_bar( int current_iteration,
                          int total_iterations,
                          int length_of_bar,
                          char filled_bar_char,
                          char non_filled_bar_char ) {
    // Calculating amount of percents reached at current iteration
    double percents = (double) current_iteration / total_iterations * 100;
    // Calculating amount of chars to fill in progress bar string
    int amount_to_fill = length_of_bar * current_iteration / total_iterations; 

    // Prepaering bar string
    char * bar_string = malloc( length_of_bar + 2 );
    bar_string[ 0 ] = '['; bar_string[ length_of_bar + 1 ] = ']';
    memset( bar_string + 1, filled_bar_char, amount_to_fill );
    memset( bar_string + amount_to_fill + 1, non_filled_bar_char, length_of_bar - amount_to_fill );

    // Printing the rendered progress string
    printf( "Progress: %s %02.1lf Completed...\n", bar_string, percents );

    // If reached 100% print new line
    if ( current_iteration == total_iterations ) printf( "\n" );
}

Результат, который я хочу получить, показан в этом видео .Код Python, который делает то же самое, но правильно:

from time import sleep

print( '[*] Starting ...' )
sleep( 1 )

for i in range( 1, 61 ) :
    # Calculating completed percents and length of bar to fill as completed
    percents    = '%.2f' % ( i / 60 * 100 )
    filled_area = int( 50 * i / 60 )

    # Preparing progress bar string
    bar_string  = ( '█' * filled_area ) + ( ' ' * ( 50 - filled_area ) )

    # Printing progress bar with some info and EOL if reached 100%
    print( '\rProgress: [%s] %s%% Completed ...\r' % ( bar_string, percents ), end = '' )
    if i == 60 : print( )

    sleep( 0.1 )

1 Ответ

0 голосов
/ 23 декабря 2018

Я не вижу пропущенных итераций.

Однако я вижу, где вычисления в процентах выполняются в целочисленной математике (которая всегда округляется), а не в double математике

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...