C++ streambuf::eback() function



The C++ std::streambuf::eback() function is used to return a pointer to the beginning of the buffer used by the stream buffer object. This pointer is used to access the data stored in the buffer, allowing for operations like modifying the content.

Syntax

Following is the syntax for std::streambuf::eback() function.

char* eback() const;

Parameters

It does not accept any parameter.

Return Value

It returns a pointer to the first element of the array with the portion of the controlled input sequence that is currently buffered.

Exceptions

If an exception is thrown, there are no changes in the stream buffer.

Data races

It accesses the stream buffer object.

Example 1

In the following example, we are going to consider the basic usage of the eback() function.

#include <iostream>
#include <streambuf>
#include <string>
class a: public std::streambuf {
   public: a(char * base, std::size_t size) {
      setg(base, base, base + size);
   }
   char c() {
      return * eback();
   }
};
int main() {
   std::string x = "Welcome";
   a mybuf( & x[0], x.size());
   std::cout << "Result : " << mybuf.c() << std::endl;
   return 0;
}

Output

Output of the above code is as follows −

Result : W

Example 2

Consider the following example, where we are going to calculate the distance form eback() to gptr().

#include <iostream>
#include <streambuf>
#include <vector>
class x: public std::streambuf {
   public: x(std::vector < char > & a) {
      setg(a.data(), a.data() + 2, a.data() + a.size());
   }
   std::ptrdiff_t y() {
      return gptr() - eback();
   }
};
int main() {
   std::vector < char > z = {'H', 'E', 'L', 'L', 'O'
   };
   x myBuf(z);
   std::ptrdiff_t distance = myBuf.y();
   std::cout << "Result : " << distance << std::endl;
   return 0;
}

Output

Following is the output of the above code −

Result : 2
streambuf.htm