RetroCoders Community

C / C ++ Programming => C / C++ => Topic started by: stigma on Jan 20, 2023, 05:36 PM

Title: Function to get Dynamic Memory Allocated Input from User in C
Post by: stigma on Jan 20, 2023, 05:36 PM
#include <stdio.h>
#include <stdlib.h>

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)
            break;

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

            if(linen == NULL) {
                free(linep);
                return NULL;
            }
            // line = linen + (line - linep);
line = linen+linelen;
            linep = linen;
        }

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

int main()
{
char * ptext = NULL;

printf("enter some text: ");

ptext = getline();

printf("\n\nthe text you entered was :\n\n");

for(; !(*ptext=='\0') ; ++ptext)
printf("%c", *ptext);

return 0;

}