Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

c - Reading in a string of unknown length from the console

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 name_buffer [ 80 ];
int chars_read = 0;
while ( ( chars_read < 80 ) && ( !feof( stdin ) ) ) {
   name_buffer [ chars_read ] = fgetc ( stdin );
   chars_read++;
}

But what can I do if the string is longer than 80 characters? Obviously I could just initialise the array to a bigger number but I'm sure there must be a better way to give the array more space using malloc or something?

Any hints would be great.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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("
Enter 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() ) != '
' && 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] = '';

        printf("
Long String value:%s 

",pStr);
        //free it 
    free(pStr);
    pStr = NULL;


    }
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...