How can I read an input string of unknown length?

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

    There is a new function in C standard for getting a line without specifying its size. getline function allocates string with required size automatically so there is no need to guess about string's size. The following code demonstrate usage:

    #include 
    #include 
    
    
    int main(void)
    {
        char *line = NULL;
        size_t len = 0;
        ssize_t read;
    
        while ((read = getline(&line, &len, stdin)) != -1) {
            printf("Retrieved line of length %zu :\n", read);
            printf("%s", line);
        }
    
        if (ferror(stdin)) {
            /* handle error */
        }
    
        free(line);
        return 0;
    }
    

提交回复
热议问题