Home > Enterprise >  Read stdin with line break in C
Read stdin with line break in C

Time:09-29

I am very new to C and I am trying to read a stdin with line breaks. A text file will be used as a stream.

from what I have learned so far, I am trying this (when running the code, < text.txt is used to get the file:

int main() {
    char textInput[100];

    fgets(textInput, 100, stdin);
    printf("%s", textInput);

    return 0;
}

and the file text is something like:

hello
my
name
is
marc

so as a result I am only Getting the Hello printed out. I am pretty sure I have to used a loop for this but I tried a bunch of things but nothing is working. I am kind of confused on how to keep printing even after encountering a line break.

CodePudding user response:

You are on the right track: you read a single line, so you only get a single line of output. To read the whole file, you must use a loop. fgets() returns the destination pointer if inout was successful and it returns NULL at the end of file, so the loop is quite simple:

#include <stdio.h>

int main() {
    char textInput[100];

    while (fgets(textInput, 100, stdin)) {
        printf("%s", textInput);
    }
    return 0;
}
  • Related