C++ streambuf::sgetc() function



The C++ std::streambuf::sgetc() function is used to access the next character in the input sequence without removing it from the buffer. This function returns the character as an int, or EOF if the end of the input sequence is reached.

Syntax

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

int_type sgetc();

Parameters

It does not accept any parameter.

Return Value

It returns the character at the current position of the controlled input sequence, converted to a value of type int_type using member traits_type::to_int_type.

Exceptions

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

Data races

It modifies the stream buffer object.

Example 1

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

#include <iostream>
#include <sstream>
int main() {
   std::stringstream x("Welcome");
   char b;
   std::streambuf * c = x.rdbuf();
   b = c -> sgetc();
   std::cout << "Result : " << b << 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 use the sgetc() function to check if the firt character in the stream matchyes a specific vale.

#include <iostream>
#include <sstream>
int main() {
   std::stringstream x("HI");
   char y;
   std::streambuf * z = x.rdbuf();
   y = z -> sgetc();
   if (y == 'H') {
      std::cout << "First Character Is Matched." << std::endl;
   } else {
      std::cout << "First Character Is Not Matched." << std::endl;
   }
   return 0;
}

Output

Following is the output of the above code −

First Character Is Matched.
streambuf.htm
Advertisements