Can you read multiple lines from stdin? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

Can you read multiple lines from stdin?

So i wanted to know if instead of using a char array variable and then the fgets function to read a single line, i could have an array of char pointers (tecnically are strings) and then use fgets?

18th Apr 2017, 12:21 PM
Jos├ę Pereira
Jos├ę Pereira - avatar
3 Antworten
+ 1
First, I think that you should have allocated memory for the lines, something like: char lines[10][10] // 10 lines of 10 chars each, you could also allocate dynamically Then you can simply read in the lines: for (int i = 0; i < 10; ++i) fgets(lines [i], 10, stdin); This is a very simple code that reads you some lines. You could extend it with some error handling and string processing to suit your needs.
25th Apr 2017, 12:40 PM
ormsson
0
I think that fgets stops reading when it encounters a new line but you could just call it multiple times in a loop and pass it the appropriate pointer each iteration.
20th Apr 2017, 4:54 PM
ormsson
0
I tried this and didn't work: char *lines[10]; //each position is one line. // Fill the array. for (int i = 0; fgets(lines[i], 10, stdin) != NULL; ++i);
20th Apr 2017, 6:21 PM
Jos├ę Pereira
Jos├ę Pereira - avatar