Reading in a string of unknown length from the console

后端 未结 2 1198
死守一世寂寞
死守一世寂寞 2020-12-10 08:18

If I want to read in a string of arbitrary length from the command line, what\'s the best way of going about it?

At the moment I\'m doing this:

char          


        
相关标签:
2条回答
  • 2020-12-10 08:31

    Use realloc() to allocate the buffer and extend it when it's full.

    0 讨论(0)
  • 2020-12-10 08:52

    Found this somewhere on the net long ago, its really useful:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        unsigned int len_max = 128;
        unsigned int current_size = 0;
    
        char *pStr = malloc(len_max);
        current_size = len_max;
    
        printf("\nEnter a very very very long String value:");
    
        if(pStr != NULL)
        {
        int c = EOF;
        unsigned int i =0;
            //accept user input until hit enter or end of file
        while (( c = getchar() ) != '\n' && c != EOF)
        {
            pStr[i++]=(char)c;
    
            //if i reached maximize size then realloc size
            if(i == current_size)
            {
                            current_size = i+len_max;
                pStr = realloc(pStr, current_size);
            }
        }
    
        pStr[i] = '\0';
    
            printf("\nLong String value:%s \n\n",pStr);
            //free it 
        free(pStr);
        pStr = NULL;
    
    
        }
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题