How can I read an input string of unknown length?

前端 未结 10 1347
逝去的感伤
逝去的感伤 2020-11-22 07:56

If I don\'t know how long the word is, I cannot write char m[6];,
The length of the word is maybe ten or twenty long. How can I use scanf to ge

10条回答
  •  花落未央
    2020-11-22 08:36

    Enter while securing an area dynamically

    E.G.

    #include 
    #include 
    
    char *inputString(FILE* fp, size_t size){
    //The size is extended by the input with the value of the provisional
        char *str;
        int ch;
        size_t len = 0;
        str = realloc(NULL, sizeof(char)*size);//size is start size
        if(!str)return str;
        while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
            str[len++]=ch;
            if(len==size){
                str = realloc(str, sizeof(char)*(size+=16));
                if(!str)return str;
            }
        }
        str[len++]='\0';
    
        return realloc(str, sizeof(char)*len);
    }
    
    int main(void){
        char *m;
    
        printf("input string : ");
        m = inputString(stdin, 10);
        printf("%s\n", m);
    
        free(m);
        return 0;
    }
    

提交回复
热议问题