C++ streambuf::gptr() function



The C++ std::streambuf::gptr() function is used to return a pointer to the current position in the input sequenece of a stream buffer. This function allows the access to the data being read, facilitating operations like peeking or manipulating input without altering the actual read position.

Syntax

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

char* gptr() const;

Parameters

It does not accepts any parameter.

Return Value

It returns a pointer to the current element of the controlled input sequence (i.e., the "get pointer").

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 gptr() function.

#include <iostream>
#include <streambuf>
class x: public std::streambuf {
   public: x(char * a, std::streamsize size) {
      this -> setg(a, a, a + size);
   }
   char * getgptr() {
      return this -> gptr();
   }
};
int main() {
   char y[] = "Welcome";
   x sb(y, sizeof(y));
   char * c = sb.getgptr();
   if (c != nullptr) {
      std::cout << "Result : " << * c << std::endl;
   } else {
      std::cout << "Null." << std::endl;
   }
   return 0;
}

Output

Output of the above code is as follows −

Result : W
streambuf.htm
Advertisements