Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming getting input

Tags:

c

algorithm

How do I constantly get user input (strings) until enter is pressed in C just like string class in C++?

I don't know the input size so I can't declare a variable of fixed size or even I can't allocate memory dynamically using malloc() or calloc().

Is there any way to implement this as a separate function?

like image 865
Praburaj Avatar asked Jun 17 '26 15:06

Praburaj


2 Answers

As H2CO3 said, you should allocate a buffer with malloc(), then resize it with realloc() whenever it fills up. Like this:

size_t bufsize = 256;
size_t buf_used = 0;
int c;
char *buf = malloc(bufsize);
if (buf == NULL) { /* error handling here */ }
while ((c = fgetc(stdin)) != EOF) {
  if (c == '\n') break;
  if (buf_used == bufsize-1) {
    bufsize *= 2;
    buf = realloc(buf, bufsize);
    if (buf == NULL) { /* error handling here */ }
  }
  buf[buf_used++] = c;
}
buf[buf_used] = '\0';
like image 156
thejh Avatar answered Jun 20 '26 06:06

thejh


Use exponential storage expansion:

char *read_a_line(void)
{
    size_t alloc_size = LINE_MAX;
    size_t len = 0;

    char *buf = malloc(LINE_MAX); // should be good for most, euh, *lines*...
    if (!buf)
       abort();

    int c;
    while ((c = fgetc(stdin)) != '\n' && c != EOF) {
        if (len >= alloc_size) {
            alloc_size <<= 1;
            char *tmp = realloc(buf, alloc_size);
            if (!tmp)
                abort(); // or whatever

            buf = tmp;
        }

        buf[len++] = c;
    }

    if (len >= alloc_size) {
        alloc_size++;
        char *tmp = realloc(buf, alloc_size);
        if (!tmp)
            abort(); // or whatever

        buf = tmp;
    }

    buf[len] = 0;
    return buf;
}