Шах Шах - 3 years ago 201
C Question

How to read input line at the end character or at '\n' character?

How can I read in C a line from the console to not initialize a some array like

int buf[30];
? I need to allocate it once and required length, i.e. to I can know input characters count before read it...

Is it possible in C?

Answer Source

There is no way to know the number of characters available in standard input before reading them. You can, however, use getline(3), which will read until \n and then return the data in a dynamically-allocated buffer holding the data (along with the size of that buffer). You must free the buffer when you're done with it.

You should be aware that this will routine will block until it reads a newline. It's also difficult to use this routine safely, as malformed inputs are not handled well. (What if the input has no newline?) This is one of the reasons many applications often read a fixed length input.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download