Search code examples
cscanf

How can I read an input string of unknown length?


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 get input from the keyboard?

#include <stdio.h>
int main(void)
{
    char  m[6];
    printf("please input a string with length=5\n");
    scanf("%s",&m);
    printf("this is the string: %s\n", m);
    return 0;
}

please input a string with length=5
input: hello
this is the string: hello


Solution

  • Enter while securing an area dynamically

    E.G.

    #include <stdio.h>
    #include <stdlib.h>
    
    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(*str)*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(*str)*(size+=16));
                if(!str)return str;
            }
        }
        str[len++]='\0';
    
        return realloc(str, sizeof(*str)*len);
    }
    
    int main(void){
        char *m;
    
        printf("input string : ");
        m = inputString(stdin, 10);
        printf("%s\n", m);
    
        free(m);
        return 0;
    }