C++ streambuf - sputc
描述
用于将字符存储在当前放置位置并增加放置指针,并将字符 c 存储在受控输出序列的当前位置,然后将位置指示符前进到下一个字符。
声明
以下是 std::streambuf::sputc 的声明。
int sputc (char c);
参数
c − 要放置的字符。
返回值
对于连续的情况,它返回字符 put,作为 int 类型的值返回。 否则,它返回文件结束值 (EOF) 以表示失败。
异常
Basic guarantee − 如果抛出异常,则流缓冲区处于有效状态。
数据竞争
它修改流缓冲区对象。
示例
在下面的例子中解释了 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;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Writing to file. Type a dot (.) to end.

