0

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)
6
  • 1
    First allocate an initial buffer for the string, with some fixed size. Then call fgets, limiting the length to the size of the buffer. If it reads less, then you can call realloc to reduce the size and you're done. But if there might be more, then call realloc to double the size of the buffer, continue reading, and repeat as needed. Commented Jun 14, 2019 at 20:32
  • You can also allocate multiple buffers and chain them together as a linked list. Commented Jun 14, 2019 at 20:33
  • If I got you right you should try to do like in this link: How to read input of unknown length using fgets Commented Jun 14, 2019 at 20:34
  • You're pretty much most definite never going to use char* text = malloc(sizeof(input)). That is, unless input happens to be a statically allocated char array (in which case, since you know the size of the static array, you would most likely not need to allocate another one dynamically). Commented Jun 14, 2019 at 20:35
  • sizeof text is the size of the pointer - irrelevant to reading user input. Commented Jun 14, 2019 at 20:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.