Advertisement
applehelpwriter

Kernighan & Ritchie Solution 1-17

Aug 31st, 2013
425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. //write a program to print all input lines that are longer than 80 characters
  2.  
  3. //a not very elegant solution to Exercise 1-17, p31
  4.  
  5. //this solution uses two concepts that K&C haven't
  6. //introduced at this stage: multi arrays and globals.
  7.  
  8. //not very happy with this but it does the job
  9.  
  10. // ~/cAgain14.c
  11.  
  12. //thoughts on better ways to do it: applehelpwriter@icloud.com
  13. //thanks!
  14.  
  15. #include <stdio.h>
  16. #define LIMIT 1000
  17. #define TEST_LENGTH 80
  18.  
  19. int k; //global
  20. int getLineLength(char s[], int a);
  21. void linesToCopy(char t[], char u[], char r[][LIMIT]);
  22.  
  23.  
  24. int main(int argc, const char * argv[]){
  25.  
  26. //declare and init:
  27. int d, e;
  28. e = k = 0;
  29. char currentLine[LIMIT];
  30. char linesToPrint[LIMIT];
  31. char lines[LIMIT][LIMIT]; //1 megabyte
  32.  
  33.  
  34. while( (d = getLineLength(currentLine, LIMIT) ) > 0){
  35.  
  36.     if (d > TEST_LENGTH){
  37.         e = d;
  38.         linesToCopy(linesToPrint, currentLine, lines);
  39.    }//end if
  40. }//end while
  41.  
  42.  
  43. printf("\n\nLines over %d characters:\n", TEST_LENGTH);
  44. if (e > TEST_LENGTH){
  45.         k = 0;
  46.         while (k < LIMIT && lines[k][d] != '\0'){
  47.             if (lines[k][d] != '\n'){
  48.                 printf("\n%d: %s", k, lines[k]);
  49.                
  50.             }
  51.             else {
  52.                   printf("\n");
  53.             }
  54.            ++k;
  55.            }
  56.        
  57. }//end if
  58.  
  59. else
  60.     printf("Sorry, no lines were more than %d characters\n", TEST_LENGTH);
  61.  
  62. return 0;
  63.  
  64. }//end main
  65.  
  66.  
  67. //this will return the length of the line
  68.  
  69. int getLineLength(char s[], int a){
  70. int c, i;
  71.  
  72. for (i = 0; i < LIMIT-1 && (c = getchar()) !=EOF && c != '\n'; ++i)
  73.     s[i] = c;
  74.  
  75. if (c == '\n'){
  76.     s[i] = c;
  77.     ++i;
  78. }//end if
  79.  
  80. s[i] = '\0';
  81. return i;
  82.  
  83. }//end getLineLength
  84.  
  85.  
  86. void linesToCopy(char t[], char u[], char r[][LIMIT]){
  87.  
  88. int i;
  89.  
  90. for (i = 0; (r[k][i] = u[i]) != '\0'; ++i){
  91.     if (u[i] == '\n')
  92.         ++k;
  93.     }//end for
  94.  
  95. }//end linesToCopy
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement