1

I'm trying to take string inputs from the user. However, the length of the strings is unknown. I know that it is necessary to declare a size for a string in C. Is there any workaround?

By the way, I'm getting the input from the command line, not from a file.

  • 1
    Please check this post -> https://stackoverflow.com/questions/8164000/how-to-dynamically-allocate-memory-space-for-a-string-and-get-that-string-from-u – Md. Faisal Habib Oct 23 '21 at 20:07
  • 1
    Use getline function if it is available on your platform. See https://man7.org/linux/man-pages/man3/getline.3.html – tstanisl Oct 23 '21 at 20:31
  • It is in the TR for C to have it too, since POSIX has defined it for ages: https://en.cppreference.com/w/c/experimental/dynamic/getline – Dúthomhas Oct 23 '21 at 22:34

1 Answers1

0

I'm allocating memory of 10 bytes for string and reading the input char by char. If the input is longer I just reallocate another 10 bytes more. The input will be stopped by 'return'.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(){

    char c = 64;
    // Allocating memory for a string of 10 bytes
    char* str = (char*) malloc(10);
    int i = 0;
    
    // Reading input char by char
    scanf("%c", &c);
    // Stop if input is 'return'   
    while ( c != 10 ){
        str[i]=c;    
        scanf("%c", &c);
        // Reallocating 10 bytes more if neccessary
        if ( i%10 == 0 ){
            str = (char *) realloc(str, i+10);
        }
        i++;
    }
    str[i]='\0';
    
    printf ("Input: %s\nLength: %ld\n", str, strlen (str));
    
return 0;
}
Guest
  • 1
  • Suggest `getchar()` instead of `scanf ("%c"...` Also consider declaring a local buffer, say `1024` bytes (or as long as needed), read with `fgets()`, trim the `'\n'` with `strcspn()` and then allocate storage to fit the input once, `memcpy()` the string (and nul-terminater) and return the allocated string. This avoids the repeated allocations of `10` bytes each. Otherwise, suggest allocating at least `64` bytes at a time and consider `realloc()` of 2X the current size each time. – David C. Rankin Oct 24 '21 at 04:47