How can I read an input string of unknown length?

前端 未结 10 1585
逝去的感伤
逝去的感伤 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:40

    i also have a solution with standard inputs and outputs

    #include
    #include
    int main()
    {
        char *str,ch;
        int size=10,len=0;
        str=realloc(NULL,sizeof(char)*size);
        if(!str)return str;
        while(EOF!=scanf("%c",&ch) && ch!="\n")
        {
            str[len++]=ch;
            if(len==size)
            {
                str = realloc(str,sizeof(char)*(size+=10));
                if(!str)return str;
            }
        }
        str[len++]='\0';
        printf("%s\n",str);
        free(str);
    }
    

提交回复
热议问题