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'
.
We can take string input in C using scanf(“%s”, str).
You can drop the & in scanf("%s",&m) since m is already a pointer to the first element of m[] in this expression.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With