C++ streambuf::sgetn() function



The C++ std::streambuf::sgetn() function is used to extract a specified number of characters from the input sequence of a stream buffer and store them in the provided array.

This function reads up to the given number of characters, modifying the stream buffers internal position accordingly. It returns the number of characters successfully extracted.

Syntax

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

streamsize sgetn (char_type* s, streamsize n);

Parameters

  • s − It indicates the pointer ti an array where the character sequence is copied.
  • n − It indicates the maximum number of characters to be retrieved.

Return Value

This function returns the number of characters copied.

Exceptions

If an exception is thrown, the stream buffer is in a valid state.

Data races

It modifies up to all of the first n characters in the array pointed by s.

Example 1

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

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf a("Welcome");
   char b[6] = {
      0
   };
   a.sgetn(b, 5);
   std::cout << "Result : " << b << std::endl;
   return 0;
}

Output

Output of the above code is as follows −

Result : Welco

Example 2

Consider the following example, where we are going to use the pubseekpos() along with the sgetn() function.

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf a("ABCDE111223");
   char b[6] = {
      0
   };
   a.pubseekpos(4);
   a.sgetn(b, 4);
   std::cout << "Result : " << b << std::endl;
   return 0;
}

Output

Following is the output of the above code −

Result : E111
streambuf.htm