Advertisement
bugaevc

Paragraph alignment problem

Nov 24th, 2014
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define print_space printf(" ")
  6.  
  7. enum { maxlen = 1000000 };
  8.  
  9. int K;
  10. char s[maxlen+1];
  11. int spaces, ln;
  12.  
  13. void clenup(void)
  14. {
  15.     s[0] = 0;
  16.     spaces = ln = 0;
  17. }
  18.  
  19. void format_string(void)
  20. {
  21.     if(spaces == 0)
  22.     {
  23.         printf("%s", s);
  24.         int i;
  25.         for(i = ln; i < K; i++)
  26.             print_space;
  27.         printf("\n");
  28.         clenup();
  29.         return;
  30.     }
  31.  
  32.     int space_size = (K-ln) / spaces,
  33.       extra_spaces = (K-ln) % spaces;
  34.  
  35.     char *c;
  36.     for(c = s; *c; c++)
  37.     {
  38.         putchar(*c);
  39.         if(*c == ' ')
  40.         {
  41.             int i;
  42.             for(i = 0; i < space_size; i++)
  43.                 print_space;
  44.             if(extra_spaces)
  45.             {
  46.                 print_space;
  47.                 extra_spaces--;
  48.             }
  49.         }
  50.     }
  51.     printf("\n");
  52.     clenup();
  53. }
  54.  
  55. int main(void)
  56. {
  57.     scanf("%d", &K);
  58.     clenup();
  59.     char new_word[K];
  60.     while(scanf("%s", new_word) != EOF)
  61.     {
  62.         if(ln)
  63.             if(ln + 1 + strlen(new_word) > K)
  64.                 format_string();
  65.         if(ln)
  66.         {
  67.             strcat(s, " ");
  68.             spaces++;
  69.             ln++;
  70.         }
  71.         strcat(s, new_word);
  72.         ln += strlen(new_word);
  73.     }
  74.     if(ln)
  75.         format_string();
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement