Write a function which gets the next input line (up to the next \n) and stores the result in a character array.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#define MAX 100

void get_line(int);

int main(int argc, char ** argv) {
    get_line(MAX);
    return 0;
}

void get_line(int N) {
    char c, line[N];
    int i;
    for (i = 0; i < N-1 && (c = getchar()) != '\n'; i++)
        line[i] = c;
    line[i] = '\0';    
}

When you compile and execute the above program on Linux, the characters read will be stored in the array line. A simple for loop as shown below can be used to view the content of the array.

for(i = 0; i != '0'; i++)
    printf("%c", line[i]);

Brief Explanation

  • The function get_line is used to get the next input line and stores the result in the array line. It does so by using the function getchar to read a character at a time from input until it reaches a new line (\n). Each character read is stored in the array line.
  • Once the for loop is exited, the variable i is one place after the last character in the array. The null character (\0) is assigned to this position to ensure termination.

Add comment


Security code
Refresh