Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C loop to read lines of input

Tags:

c

loops

I want to create a program in C that takes an arbitrary number of lines of arbitrary length as input and then prints to console the last line that was inputted. For example:

input:

hi
my name is
david

output: david

I figured the best way to do this would be to have a loop that takes each line as input and stores it in a char array, so at the end of the loop the last line ends up being what is stored in the char array and we can just print that.

I have only had one lecture in C so far so I think I just keep setting things up wrong with my Java/C++ mindset since I have more experience in those languages.

Here is what I have so far but I know that it's nowhere near correct:

#include <stdio.h>

int main()
{
    printf("Enter some lines of strings: \n");

    char line[50];

    for(int i = 0; i < 10; i++){
        line = getline(); //I know this is inproper syntax but I want to do something like this
    }

    printf("%s",line);


}

I also have i < 10 in the loop because I don't know how to find the total number of lines in the input which, would be the proper amount of times to loop this. Also, the input is being put in all at once from the

./program < test.txt 

command in Unix shell, where test.txt has the input.

like image 509
David - Avatar asked Jan 27 '23 08:01

David -


1 Answers

Use fgets():

while (fgets(line, sizeof line, stdin)) {
    // don't need to do anything here
}
printf("%s", line);

You don't need a limit on the number of iterations. At the end of the file, fgets() returns NULL and doesn't modify the buffer, so line will still hold the last line that was read.

like image 193
Barmar Avatar answered Jan 30 '23 07:01

Barmar