Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Критерий - совмещение логики обработки данных и вывода в stdout #11

Open
AndrewGavril opened this issue Dec 29, 2023 · 2 comments

Comments

@AndrewGavril
Copy link

Часто происходит одновременная обработка и вывод результата на экран -- чего нужно избегать

@zmm
Copy link
Contributor

zmm commented Dec 29, 2023

@AndrewGavril покажите, пожалуйста, пример - как правильно и как не правильно (и желательно возможные исключения из правила:)

@AndrewGavril
Copy link
Author

Плохой пример:

void search_time(char** array_text, int *count_sentence){
    for(int i = 0; i < *count_sentence; i++){
        int hours = 0;
        int minutes = 0;
        int seconds = 0;
        int flag = 0;
        char* word;
        while((word = strtok(array_text[i], " ,")) != NULL){
            array_text[i] = NULL;
            if(strstr(word, "sec") != NULL){
                int sec;
                if (sscanf(word, "%dsec", &sec) == 1){
                    seconds += sec;
                    flag = 1;
                }
            }
        }
        if(flag){
        minutes = seconds / 60;
        seconds = seconds % 60;
        hours = minutes / 60;
        minutes = minutes % 60;
        printf("%02d:%02d:%02d\n", hours, minutes, seconds);
        }
    }
}

В данном случае происходит поиск шаблона в строке и преобразования в строку другого вида, совмещенной с выводом в stdout, Последствия такого вывода таковы, что может быть очень сложно найти всю последовательность функций из которых склеивается строка в потоке вывода (к тому же такое решение не будет работать в многопоточном режиме, но к этому курсу это не относится).
Лучше так:

#define TIME_STR_LEN 10
void search_time(char** array_text, int *count_sentence){
    for(int i = 0; i < *count_sentence; i++){
        int hours = 0;
        int minutes = 0;
        int seconds = 0;
        int flag = 0;
        char* word;
        while((word = strtok(array_text[i], " ,")) != NULL){
            array_text[i] = NULL;
            if(strstr(word, "sec") != NULL){
                int sec;
                if (sscanf(word, "%dsec", &sec) == 1){
                    seconds += sec;
                    flag = 1;
                }
            }
        }
        char * result_str = NULL;
        if(flag){
          result_str = malloc(TIME_STR_LEN * sizeof(char));
          minutes = seconds / 60;
          seconds = seconds % 60;
          hours = minutes / 60;
          minutes = minutes % 60;
          sprintf(result_str, "%02d:%02d:%02d\n", hours, minutes, seconds);
        }
        return result_str;
    }
}
...
char **process_text(char** array_text, int *count_sentences){
    /* итерации по предложениями */
    char *time_str;
    ...
    time_str = search_time(array_text, i);
    /* конкатенация всех подстрок предложения*/
    retun result_text;
}

/* в отдельной функции вывода результата циклический обход предложений и вывод строк */

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants