pbreault pbreault - 1 year ago 175
C Question

How to read a line from the console in C?

What is the simplest way to read a full line in a C console program
The text entered might have a variable length and we can't make any assumption about its content.

Answer Source

You need dynamic memory management, and use the fgets function to read your line. However, there seems to be no way to see how many characters it read. So you use fgetc:

char * getline(void) {
    char * line = malloc(100), * linep = line;
    size_t lenmax = 100, len = lenmax;
    int c;

    if(line == NULL)
        return NULL;

    for(;;) {
        c = fgetc(stdin);
        if(c == EOF)

        if(--len == 0) {
            len = lenmax;
            char * linen = realloc(linep, lenmax *= 2);

            if(linen == NULL) {
                return NULL;
            line = linen + (line - linep);
            linep = linen;

        if((*line++ = c) == '\n')
    *line = '\0';
    return linep;

Note: Never use gets ! It does not do bounds checking and can overflow your buffer

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