Thread: String

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    35

    String

    This is it:
    Code:
    #include <stdio.h>
    
    #define MAXLINE 1000
    
    
    int getline(char line[], int maxline);
    void copy(char to[], char from[]);
    
    
    main()
    {
        int len;
        int max;
        int line[MAXLINE];
        int longest[MAXLINE];
    
    
        max = 0;
        while ((len = getline(line, MAXLINE)) > 0) {
            printf("%d = %s", len, line);
            if(len > max) {
                max = len;
                copy (longest, line);
            }
        }
        if (max > 0)
            printf("%s", longest);
        return 0;
    }
    
    
     int getline(char s[], int lim)
     {
         int c, i, j;
         j = 0;
         for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
         if (i < lim-2) {
            s[j] = c;
            ++j;
    
    
         }
         if (c == '\n') {
            s[j] = c;
            ++j;
    
    
         }
         s[j] = '\0';
         return i;
     }
     void copy(char to[], char from[])
     {
         int i;
         i = 0;
         while((to[i] = from[i]) != '\0')
            ++i;
         }
    I preety much understand everything.But can anyone explain to me
    line 33.The condition for lim-2.What does lim-2 mean.A bit detail would be nice.Cuz this is the piece of code i don't understand.
    And its messing up my understanding of the other parts.
    So if anyone could please.
    Thank you!

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    he condition for lim-2.What does lim-2 mean.
    Since you seem to be trying to emulate the getline() provided by the POSIX getline() function you may want to look at the documentation for this funciton. This paragraph should explain the lim - 2:

    The buffer is null-terminated and includes the newline character, if one was found.
    You need to insure that you properly null-terminate the string and add the newline character if it was found. Since you are exiting the loop if you find a newline character without appending it to the buffer you must insure you have room for this character along with the end of string character.

    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-01-2013, 10:11 PM
  2. Replies: 1
    Last Post: 04-27-2013, 04:36 AM
  3. Replies: 22
    Last Post: 07-28-2011, 01:26 PM
  4. Replies: 7
    Last Post: 06-16-2011, 06:21 PM
  5. Replies: 1
    Last Post: 10-31-2005, 11:36 AM