How can I read an input string of unknown length?

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

    Safer and faster (doubling capacity) version:

    char *readline(char *prompt) {
      size_t size = 80;
      char *str = malloc(sizeof(char) * size);
      int c;
      size_t len = 0;
      printf("%s", prompt);
      while (EOF != (c = getchar()) && c != '\r' && c != '\n') {
        str[len++] = c;
        if(len == size) str = realloc(str, sizeof(char) * (size *= 2));
      }
      str[len++]='\0';
      return realloc(str, sizeof(char) * len);
    }
    

提交回复
热议问题