Guest User

Untitled

a guest
May 16th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4.  
  5. // Write a program to fold long input lines into 2 shorter lines
  6. // after first nonblank character. Take care of very long lines,
  7. // and if there's no blanks/tabs before column
  8. // Essentially a string tokenizer
  9.  
  10. int length(char input[]);
  11.  
  12. int main(int argc, char* argv[])
  13. {
  14.  
  15. if(argc < 3)
  16. {
  17. printf("Usage: %s input [n]\n", argv[0]);
  18. exit(1);
  19. }
  20.  
  21. int COL_BOUND = atof(argv[2]);
  22.  
  23. int startCol, currentCut, nextBound, numOfCuts;
  24.  
  25. startCol = currentCut = nextBound = numOfCuts = 0;
  26.  
  27. //while the next bound is still "inside" string
  28. while((nextBound = startCol + COL_BOUND - 1) <= length(argv[1]))
  29. {
  30. //find cut character
  31. for(int i = startCol; i <= nextBound; ++i)
  32. {
  33. if(isspace(argv[1][i]) && !isspace(argv[1][i-1]))
  34. currentCut = i - 1;
  35. }
  36. //there was no valid "cut" before whitespace or bound itself is valid
  37. if(!isspace(argv[1][nextBound]) || currentCut <= startCol)
  38. currentCut = nextBound;
  39.  
  40. //print [startCol, cut]
  41. int printed = 0;
  42. for(int i = startCol; i <= currentCut; ++i)
  43. {
  44. if(isspace(argv[1][i]) && printed == 0)
  45. continue;
  46. ++printed;
  47. putchar(argv[1][i]);
  48. }
  49.  
  50. printf("\n");
  51.  
  52. //adjust start column for the next run
  53. startCol = startCol + COL_BOUND;
  54. ++numOfCuts;
  55. }
  56.  
  57. //print remaining characters
  58. int printed = 0;
  59. ++numOfCuts;
  60. for(int i=startCol; i <= length(argv[1]); ++i)
  61. {
  62. if(isspace(argv[1][i]) && printed == 0)
  63. continue;
  64. ++printed;
  65. putchar(argv[1][i]);
  66. }
  67.  
  68. printf("\nOriginal string split into %d parts (bound was %d)\n", numOfCuts, COL_BOUND);
  69. return 0;
  70. }
  71.  
  72. int length(char input[])
  73. {
  74. int i;
  75. for(i=0; input[i] != '\0'; ++i)
  76. ;
  77. return i;
  78. }
Add Comment
Please, Sign In to add comment