Advertisement
heavenriver

maxstring.c

Nov 23rd, 2013
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | None | 0 0
  1. /* analyses the file and prints the longest string */
  2.  
  3.  /* pointer arithmetics:
  4.   *
  5.   * push(pointer, v) INDICATES *(pointer++) = v
  6.   * pop(pointer) INDICATES *(--pointer)
  7.   * (*++v)[0] INDICATES (**++v)
  8.   *           INDICATES first char in v
  9.   *           INDICATES name of string/vector v
  10.   * likewise, *v[0] INDICATES **v
  11.   *       and *v[n] INDICATES **(v + n)
  12.   * returntype (*funct)(args) INDICATES a function funct with arguments args which returns...
  13.   * char **argv INDICATES pointer to char pointer
  14.   * int(*v)[len] INDICATES pointer "v" to a vector of "len" int elements
  15.   * int *v[len] INDICATES vector "v" of "len" pointers to int elements
  16.   * void *funct() INDICATES function "funct" that returns a pointer-to-void
  17.   * void (*funct)() INDICATES pointer to a function "funct" that returns void
  18.   *
  19.   */
  20.  
  21.  /* useful characters: [] # */
  22.  
  23.  # include <stdio.h>
  24.  # define MAXL 1000 // maximum line length
  25.  
  26. /* copies the string to another char array */    
  27.  
  28. void copy(char to[], char from[])
  29.     {
  30.     int i = 0;
  31.     for(i = 0; (to[i] = from[i]) != '\0'; i++)
  32.     // stops copying when the source is out of chars
  33.     ;
  34.     }
  35.  
  36. /* returns the length of a line */
  37.  
  38. int getlineX(char line[], int limit)
  39.     {
  40.       int c, i;
  41.       for(i = 0; i < limit-1 && (c = getchar()) != EOF && c != '\n'; i++)
  42.       {
  43.         line[i] = c; // the new char is copied
  44.         if(c == '\n') // if end of line, the new char is copied
  45.           {
  46.         line[i] = c;
  47.         ++i;
  48.           }
  49.       }
  50.       line[i] = '\0'; // marks end of line
  51.       return i;
  52.     }
  53.  
  54. /* main */
  55.  
  56. int main(int argc, char * argv[])
  57.     {
  58.       int length, max; // length of the current, and maximum, string
  59.       length = max = 0;
  60.       char lines[MAXL]; // input line
  61.       char longest[MAXL]; // longest line
  62.      
  63.       while((length = getlineX(lines, MAXL)) > 0) // examines all line lengths
  64.       {
  65.        if(length > max)
  66.           {
  67.         max = length;
  68.         copy(longest, lines); // updates longest line
  69.           }
  70.       }
  71.      
  72.       if(max > 0)
  73.       printf("%s\n", longest); // prints the longest line, if non-null
  74.       return 0;
  75.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement