How can I read an input string of unknown length?

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

    Read directly into allocated space with fgets().

    Special care is need to distinguish a successful read, end-of-file, input error and out-of memory. Proper memory management needed on EOF.

    This method retains a line's '\n'.

    #include 
    #include 
    
    #define FGETS_ALLOC_N 128
    
    char* fgets_alloc(FILE *istream) {
      char* buf = NULL;
      size_t size = 0;
      size_t used = 0;
      do {
        size += FGETS_ALLOC_N;
        char *buf_new = realloc(buf, size);
        if (buf_new == NULL) {
          // Out-of-memory
          free(buf);
          return NULL;
        }
        buf = buf_new;
        if (fgets(&buf[used], (int) (size - used), istream) == NULL) {
          // feof or ferror
          if (used == 0 || ferror(istream)) {
            free(buf);
            buf = NULL;
          }
          return buf;
        }
        size_t length = strlen(&buf[used]);
        if (length + 1 != size - used) break;
        used += length;
      } while (buf[used - 1] != '\n');
      return buf;
    }
    

    Sample usage

    int main(void) {
      FILE *istream = stdin;
      char *s;
      while ((s = fgets_alloc(istream)) != NULL) {
        printf("'%s'", s);
        free(s);
        fflush(stdout);
      }
      if (ferror(istream)) {
        puts("Input error");
      } else if (feof(istream)) {
        puts("End of file");
      } else {
        puts("Out of memory");
      }
      return 0;
    }
    

提交回复
热议问题