public member function
<streambuf> <iostream>
int_type sputc (char_type c);
Put character and advance to next position
The character c is stored at the current position of the controlled output sequence, and then advances the position indicator to the next character.
Internally, the function calls the virtual protected member overflow if there are no write positions available at the put pointer (pptr). Otherwise, the function uses the put pointer (pptr) directly, without calling virtual member functions.
其行为等同于如下实现:
1 2 3 4 5 6 7
|
int_type sputc(char_type c) {
if ( (!pptr()) || (pptr()==epptr()) )
return overflow(traits_type::to_int_type(c));
*pptr()=c;
pbump(1);
return traits_type::to_int_type(c);
}
|
参数
- c
- Character to be put.
成员类型 char_type 是流缓冲区(第一个类模板参数)中字符的类型。
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// typewriter - sputc() example
#include <iostream> // std::cin, std::cout, std::streambuf
#include <fstream> // std::ofstream
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;
}
|
This example code writes every character to a file until a dot character (.
) is introduced.
数据竞争
修改*流缓冲区*对象。
同时访问同一*流缓冲区*对象可能会导致数据竞争。
异常安全
基本保证:如果抛出异常,则流缓冲区处于有效状态(这也适用于标准派生类)。