Search code examples
cwhile-loopfgetspointer-arithmetic

Using fgets for multiple lines with stdin


I'm new to C programming, and I'm trying to store multiple lines from stdin into an array. I succeeded in storing each line in the array, but it doesn't append the new lines but just store it over the current content of the array.

I don't know how to specify that it should append the lines at the end of the current content of the array. Could someone show me how to proceed? Here is my code:

#include <stdio.h>

char line[150];

while (fgets(line,20,stdin) != NULL){

}
printf("%s",line);

stdin:

Hi
 tv
truck

What it's currently printing:

truck

What I want to print but don't know how to append the lines:

Hi
 tv
truck

The content of line should be:

[H,i,\n,' ',t,v,\n,t,r,u,c,k]

Solution

  • You need something like the following

    size_t n = 0;
    
    while ( fgets( line + n,20,stdin) != NULL)
    {
        n += strlen( line + n );
    }
    

    If you need to remove the last new line character '\n' then after the loop you can add the following statement

    if ( line[n-1] == '\n' ) line[n-1] = '\0';