How can I read an input string of unknown length?

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

    I know that I have arrived after 4 years and am too late but I think I have another way that someone can use. I had used getchar() Function like this:-

    #include 
    #include 
    #include 
    
    //I had putten the main Function Bellow this function.
    //d for asking string,f is pointer to the string pointer
    void GetStr(char *d,char **f)
    {
        printf("%s",d);
    
        for(int i =0;1;i++)
        {    
            if(i)//I.e if i!=0
                *f = (char*)realloc((*f),i+1);
            else
                *f = (char*)malloc(i+1);
            (*f)[i]=getchar();
            if((*f)[i] == '\n')
            {
                (*f)[i]= '\0';
                break;
            }
        }   
    }
    
    int main()
    {
        char *s =NULL;
        GetStr("Enter the String:- ",&s);
        printf("Your String:- %s \nAnd It's length:- %lu\n",s,(strlen(s)));
        free(s);
    }
    

    here is the sample run for this program:-

    Enter the String:- I am Using Linux Mint XFCE 18.2 , eclispe CDT and GCC7.2 compiler!!
    Your String:- I am Using Linux Mint XFCE 18.2 , eclispe CDT and GCC7.2 compiler!! 
    And It's length:- 67
    

提交回复
热议问题