fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. class BufferedStreamBuf : public streambuf
  7. {
  8. streambuf *buf;
  9. vector<int_type> buffer;
  10. streampos pos;
  11. public:
  12. BufferedStreamBuf(streambuf* buf): buf(buf), pos(0) { }
  13. BufferedStreamBuf(const BufferedStreamBuf&) = delete;
  14. BufferedStreamBuf& operator=(const BufferedStreamBuf&) = delete;
  15. protected:
  16. virtual int_type underflow()
  17. {
  18. if (pos == buffer.size())
  19. {
  20. int_type c = buf->sbumpc();
  21. buffer.push_back(c);
  22. return c;
  23. }
  24. else if (pos < buffer.size())
  25. {
  26. return buffer[pos];
  27. }
  28. else
  29. {
  30. return EOF;
  31. }
  32. }
  33. virtual int_type uflow()
  34. {
  35. if (pos >= buffer.size())
  36. {
  37. int_type c = buf->sbumpc();
  38. buffer.push_back(c);
  39. pos += 1;
  40. return c;
  41. }
  42. else
  43. {
  44. return buffer[pos+=1];
  45. }
  46. }
  47. virtual streampos seekoff(streamoff off, ios_base::seekdir way, ios_base::openmode which)
  48. {
  49. if (which == ios_base::in)
  50. {
  51. if (way == ios_base::beg and off >= 0)
  52. {
  53. while (off >= buffer.size())
  54. uflow();
  55. pos = off;
  56. }
  57. if (way == ios_base::cur)
  58. {
  59. streampos new_pos = off + pos;
  60. while (new_pos >= buffer.size())
  61. uflow();
  62. pos = new_pos;
  63. }
  64. if (way == ios_base::end)
  65. {
  66. // Kann man später noch richtig machen. Erst einmal Fehler
  67. return pos_type(off_type(-1));
  68. }
  69. }
  70. return 0;
  71. }
  72. virtual streampos seekpos(streampos newp, ios_base::openmode which)
  73. {
  74. cerr << "Seekpos called.\n";
  75. if (which == ios_base::in)
  76. {
  77. while (newp >= buffer.size())
  78. uflow();
  79. pos = newp;
  80. }
  81. return 0;
  82. }
  83. };
  84.  
  85.  
  86. int main()
  87. {
  88. BufferedStreamBuf buffered_cin_streambuf(cin.rdbuf());
  89. istream buffered_cin(&buffered_cin_streambuf);
  90. int i;
  91. buffered_cin >> i;
  92. cout << i << '\n';
  93. int j;
  94. buffered_cin.seekg(1, ios::beg);
  95. buffered_cin >> j;
  96. cout << j << '\n';
  97. }
  98.  
Success #stdin #stdout 0s 2992KB
stdin
123
stdout
123
23