C++ streambuf - sputc



Description

It is used to store character at current put position and increase put pointer and the character c is stored at the current position of the controlled output sequence, and then advances the position indicator to the next character.

Declaration

Following is the declaration for std::streambuf::sputc.

int sputc (char c);

Parameters

c − Character to be put.

Return Value

It returns for successive case, the character put is returned, as a value of type int. Otherwise, it returns the end-of-file value (EOF) to signal a failure.

Exceptions

Basic guarantee − if an exception is thrown, the stream buffer is in a valid state.

Data races

It modifies the stream buffer object.

Example

In below example explains about std::streambuf::sputc.

#include <iostream>     
#include <fstream>      

int main () {
   char ch;
   std::ofstream ostr ("test.txt");
   if (ostr) {
      std::cout << "Writing to file. Type a dot (.) to end.\n";
      std::streambuf * pbuf = ostr.rdbuf();
      do {
         ch = std::cin.get();
         pbuf->sputc(ch);
      } while (ch!='.');
      ostr.close();
   }
   return 0;
}

Let us compile and run the above program, this will produce the following result −

Writing to file. Type a dot (.) to end.
streambuf.htm
Advertisements