in one of my C projects I need to read multiple lines. Let's say I expect some list of instructions, so the input might look like this (of course I don't know the maximal length):
1. First do this...
2. After that...
...
n. Finish doing this...
I want to store this data somewhere (in file,..), because afterwards I want to be able search in many similar lists, etc.
I came up with the idea of using cycle and reading one character at the time, and I made this piece of code(bit simplified):
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
char *stream;
int i=0;
stream = (char *)malloc(sizeof(char));
do{
stream = (char *)realloc(stream,(i+1)*sizeof(char)); // Reallocating memory for next character
stream[i] = getc(stdin); // Reading from stdin
if( i>0 && stream[i-1]=='\n' && stream[i]== '\n' ) // Stop reading after hitting ENTER twice in a row
break;
i++;
}while(1); // Danger of infinite cycle - might add additional condition for 'i', but for the sake of question unnecessary
printf("%s\n", stream); // Print the result
free(stream); // And finally free the memory
return 0;
}
This piece of code actually works, but it seems to me that this is quite messy solution (the user might want to add more blank lines '\n' to make the list more readable - but then, after changing the 'if' condition there would be the need of hitting the ENTER many times).