ARD
ARD

Reputation: 333

String array as long as input

In C, I want to take an input from the user but I don't know how long is it. I think I should use malloc() to set the length of the text array:

char *text = NULL;
text = malloc(sizeof(input))

But, how can I do it at the same time that I'm storing the input to the array with fgets()?

fgets(text, sizeof text, stdin)

Upvotes: 0

Views: 72

Answers (1)

dbush
dbush

Reputation: 224362

The string stored as a result of calling fgets will contain a newline if it can fit in the buffer. If the read string ends in a newline you know you have a full line. If not, you know you need to read more.

So start by using malloc to allocate a buffer of a certain size. Then use fgets to populate the buffer. If there's no newline in the buffer, use realloc to expand it and use fgets again, starting at the offset you left off at.

Alternately, if you're on a POSIX system like Linux you can just use getline which does all of this for you.

Upvotes: 1

Related Questions