fork download
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. using namespace std;
  5.  
  6. int main(void)
  7. {
  8. char *buffer = NULL;
  9. size_t bufferSize = 0;
  10. size_t count = 0;
  11. char c;
  12.  
  13. while(cin.get(c) && c != '\n')
  14. {
  15. // Resize the buffer if we need more space.
  16. if(count + 2 > bufferSize) // bufferSize includes null terminator.
  17. {
  18. // Store information about the original one.
  19. char *old = buffer;
  20. size_t oldSize = bufferSize;
  21.  
  22. // Calculate new size.
  23. bufferSize = ((count + 2) / 5 + 1) * 5;
  24. cout << "current length : " << count << " new size : " << bufferSize << endl;
  25.  
  26. // Allocate using new size.
  27. buffer = new char[bufferSize];
  28.  
  29. // Copy from the old one.
  30. memcpy(buffer, old, oldSize);
  31.  
  32. delete [] old;
  33. }
  34.  
  35. buffer[count] = c;
  36. ++count;
  37. }
  38.  
  39. // Add null terminator.
  40. buffer[count] = '\0';
  41.  
  42. cout << buffer << endl;
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0.01s 2860KB
stdin
Hello world!
stdout
current length : 0  new size : 5
current length : 4  new size : 10
current length : 9  new size : 15
Hello world!