Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main() {
  5.     FILE *file;
  6.     char str[1000];
  7.  
  8.     // Otcrivaem file
  9.     file = fopen_s("input.txt", "r");
  10.     if (file == NULL){
  11.         printf("Could not open file input.txt");
  12.         return 1;
  13.     }
  14.  
  15.     // Zaprashivaem shirinu stroki
  16.     int lineWidth;
  17.     printf("Enter line width:\n");
  18.     scanf_s("%d", &lineWidth);
  19.     if (lineWidth <= 0) {
  20.         printf("Incorrect line width");
  21.         return 1;
  22.     }
  23.  
  24.     // Tekushaya dlina - 0
  25.     int currentLineWidth = 0;
  26.     // Poka est' stroki v texte
  27.     while (fgets(str, 1000, file) != NULL) {
  28.         // Opredelyaem ocherednoy token do probela ili perevoda stroki
  29.         char * token = strtok_s(str, " \n");
  30.         // Esli on nayden
  31.         while (token != NULL) {
  32.             // Opredelyaem dlinu tokena
  33.             int tokenLength = strlen(token);
  34.  
  35.             // Esli on ne vlezaet v tekushuu stroku, to perehodim na sleduushuu
  36.             // Otdel'no proveryaem, chto slovo ne dlinnee shirini stroki (to est' ne vlezaet s samogo nachala)
  37.             if (tokenLength  + (currentLineWidth > 0 ? 1 : 0) > lineWidth - currentLineWidth && currentLineWidth > 0) {
  38.                 printf("\n");
  39.                 // Posle perevoda stroki dlina ravna 0
  40.                 currentLineWidth = 0;
  41.             }
  42.  
  43.             // Esli stroka ne novaya, to nujno dobavit' probel
  44.             if (currentLineWidth > 0) {
  45.                 printf(" ");
  46.                 currentLineWidth++;
  47.             }
  48.  
  49.             // Vivodim token
  50.             printf("%s", token);
  51.  
  52.             // Uvelichivaem dlinu stroki na dlinu tokena
  53.             currentLineWidth += tokenLength;
  54.  
  55.             // Ishem ocherednoy token
  56.             token = strtok_s(NULL, " \n");
  57.         }
  58.     }
  59.     // Zakrivaem file
  60.     fclose(file);
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement