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

前端 未结 3 955
说谎
说谎 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.

    0 讨论(0)
  • 2021-01-21 10:56

    If this can use C++, you can use string (std::string) which will grow as needed as characters are added. If you can't then you will have to use malloc to create an array to hold characters. When it is full, you will have to create a new one, and copy the current data from old to new one, then add the new character. You can do that on each character read to use the minimal amount of memory, but that is WAY too inefficient. A better way is to allocate the character array in chucks, keeping the current size, and the number of characters currently in it. When you want to add another character and the array is full, then you allocate a new one that is some number of characters larger than current one, update current size to size of new one, then add new character.

    0 讨论(0)
  • 2021-01-21 11:01

    You can read character at a time and copy it into your essay buffer. When your essay buffer runs out of space, you can do a realloc to get another chunk of memory. When your character that you read is a "#" you're done.

    0 讨论(0)
提交回复
热议问题