How can I read a paragraph in via the terminal as a single string in C?

前端 未结 3 959
说谎
说谎 2021-01-21 10:27

I\'m writing a C program that should read in an essay from a user. The essay is divided into multiple paragraphs. I don\'t know how many lines or characters the essay will be,

3条回答
  •  遥遥无期
    2021-01-21 10:37

    Hmmm to "not waste space in memory",

    then how about excessive calls of realloc()?

    char *Read_Paragraph_i(void) {
      size_t size = 0;
      size_t i = 0;
      char *dest = NULL; 
      int ch;
      while ((ch = fgetc(stdin)) != EOF) {
        if (ch == '#') break;
        size++;
        char *new_ptr = realloc(dest, size);
        assert(new_ptr);
        dest = new_ptr;
        dest[i++] = ch;
      }
      size++;
      char *new_ptr = realloc(dest, size+);
      assert(new_ptr);
      dest = new_ptr;
      dest[i++] = '\0';
      return dest;
    }
    

    A more sane approach would double the allocation size every time more memory is need, temporally wasting memory and then a final "right-size" allocation.

提交回复
热议问题