How can I read an input string of unknown length?

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

    With the computers of today, you can get away with allocating very large strings (hundreds of thousands of characters) while hardly making a dent in the computer's RAM usage. So I wouldn't worry too much.

    However, in the old days, when memory was at a premium, the common practice was to read strings in chunks. fgets reads up to a maximum number of chars from the input, but leaves the rest of the input buffer intact, so you can read the rest from it however you like.

    in this example, I read in chunks of 200 chars, but you can use whatever chunk size you want of course.

    #include 
    #include 
    #include 
    
    char* readinput()
    {
    #define CHUNK 200
       char* input = NULL;
       char tempbuf[CHUNK];
       size_t inputlen = 0, templen = 0;
       do {
           fgets(tempbuf, CHUNK, stdin);
           templen = strlen(tempbuf);
           input = realloc(input, inputlen+templen+1);
           strcpy(input+inputlen, tempbuf);
           inputlen += templen;
        } while (templen==CHUNK-1 && tempbuf[CHUNK-2]!='\n');
        return input;
    }
    
    int main()
    {
        char* result = readinput();
        printf("And the result is [%s]\n", result);
        free(result);
        return 0;
    }
    

    Note that this is a simplified example with no error checking; in real life you will have to make sure the input is OK by verifying the return value of fgets.

    Also note that at the end if the readinput routine, no bytes are wasted; the string has the exact memory size it needs to have.

提交回复
热议问题