The condition is:
I want to input a line from standard input, and I don't know the size of it, maybe very long.
method like scanf
, gets
need to know the max length you may input, so that your input size is less than your buffer size.
So Is there any good ways to handle it?
Answer must be only in C, not C++, so c++ string is not what I want. I want is C standard string, something like char*
and end with '\0'
.
The C standard doesn't define such a function, but POSIX does.
The getline
function, documented here (or by typing man getline
if you're on a UNIX-like system) does what you're asking for.
It may not be available on non-POSIX systems (such as MS Windows).
A small program that demonstrates its usage:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *line = NULL;
size_t n = 0;
ssize_t result = getline(&line, &n, stdin);
printf("result = %zd, n = %zu, line = \"%s\"\n", result, n, line);
free(line);
}
As with fgets
, the '\n'
newline character is left in the array.