Thread: K&R Chapter 1 - basic question

  1. #1
    Registered User
    Join Date
    May 2013
    Posts
    2

    K&R Chapter 1 - basic question

    Hi,

    I am new to C and I have a very basic question regarding the example in paragraph 1.9 of K&R (reproduced below).

    I managed to run the program through the Terminal of my Mac, but I do not understand how it works. Especially, I do not understand how the program captured my input and fed it as an argument to the getline_kr function. Indeed, I do not see the array line being assigned to a value anywhere. I would have expected a statement akin to the raw_input() function in Python.

    Could anyone explain how the text that I type in the terminal after the program is launched ends up being assigned to the line array????

    Thank you for your help.

    Code:
    #include <stdio.h>
    
    
    #define MAXLINE 1000
    
    
    int getline_kr(char line[], int maxline);
    void copy(char to[], char from[]);
    
    
    int main(void)
    {
    int len; /* current line length */
    int max; /* maximum length seen so far */
    char line[MAXLINE]; /* current input line */
    char longest[MAXLINE]; /* longest line saved here */
    
        max = 0;
    
        while ((len = getline_kr(line, MAXLINE)) > 0) /* QUESTION: WHERE IS LINE ASSIGNED A VALUE??????? */
            if (len > max) {
                max = len;
                copy(longest, line);
            }
    
    if (max > 0) /* there was a line */
            printf("%s", longest);
        return 0;
    }
    
    
    /* getline: read a line into s, return length */
    
    
    int getline_kr(char s[], int lim)
    {
        int c, i;
    
        for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; i++)
            s[i] = c;
    
        if (c == '\n') {
            s[i] = c;
            ++i;
        }
    
        s[i] = '\0';
        return i;
    }
    
    
    /* copy: copy 'from' into 'to'; assume its big enough */
    
    
    void copy(char to[], char from[])
    {
        int i;
    
        i = 0;
        while ((to[i] = from[i]) != '\0')
            ++i;
    }
    
    

  2. #2
    Registered User
    Join Date
    May 2013
    Posts
    2
    Ah, I think I get it. It is the getchar() function that reads my input one character at a time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 03-23-2011, 09:00 AM
  2. C++ Accelerated Questions Chapter 1.
    By Kitt3n in forum C++ Programming
    Replies: 7
    Last Post: 07-19-2010, 06:23 PM
  3. debug problem --> chapter 5.6 K&R
    By c_lady in forum C Programming
    Replies: 2
    Last Post: 06-18-2010, 03:26 AM
  4. K&R chapter 8
    By Tool in forum C Programming
    Replies: 9
    Last Post: 02-22-2010, 02:05 PM
  5. Visual C++ 6 Bible [Chapter 7]
    By Dual-Catfish in forum Windows Programming
    Replies: 6
    Last Post: 03-12-2002, 01:15 PM

Tags for this Thread