Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- int main() {
- FILE *file;
- char str[1000];
- // Otcrivaem file
- file = fopen_s("input.txt", "r");
- if (file == NULL){
- printf("Could not open file input.txt");
- return 1;
- }
- // Zaprashivaem shirinu stroki
- int lineWidth;
- printf("Enter line width:\n");
- scanf_s("%d", &lineWidth);
- if (lineWidth <= 0) {
- printf("Incorrect line width");
- return 1;
- }
- // Tekushaya dlina - 0
- int currentLineWidth = 0;
- // Poka est' stroki v texte
- while (fgets(str, 1000, file) != NULL) {
- // Opredelyaem ocherednoy token do probela ili perevoda stroki
- char * token = strtok_s(str, " \n");
- // Esli on nayden
- while (token != NULL) {
- // Opredelyaem dlinu tokena
- int tokenLength = strlen(token);
- // Esli on ne vlezaet v tekushuu stroku, to perehodim na sleduushuu
- // Otdel'no proveryaem, chto slovo ne dlinnee shirini stroki (to est' ne vlezaet s samogo nachala)
- if (tokenLength + (currentLineWidth > 0 ? 1 : 0) > lineWidth - currentLineWidth && currentLineWidth > 0) {
- printf("\n");
- // Posle perevoda stroki dlina ravna 0
- currentLineWidth = 0;
- }
- // Esli stroka ne novaya, to nujno dobavit' probel
- if (currentLineWidth > 0) {
- printf(" ");
- currentLineWidth++;
- }
- // Vivodim token
- printf("%s", token);
- // Uvelichivaem dlinu stroki na dlinu tokena
- currentLineWidth += tokenLength;
- // Ishem ocherednoy token
- token = strtok_s(NULL, " \n");
- }
- }
- // Zakrivaem file
- fclose(file);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement