Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any function to get an unlimited input string from standard input

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, getsneed 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'.

like image 236
Daizy Avatar asked Dec 14 '14 04:12

Daizy


People also ask

Which function is used for taking string input?

We can take string input in C using scanf(“%s”, str).

How do you take an unknown size input?

You can drop the & in scanf("%s",&m) since m is already a pointer to the first element of m[] in this expression.


1 Answers

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.

like image 68
Keith Thompson Avatar answered Oct 04 '22 17:10

Keith Thompson