public member function
<streambuf> <iostream>

std::streambuf::sputc

int sputc (char c);
在當前寫入位置儲存字元並增加寫入指標
字元 c 被儲存在受控輸出序列的當前位置,然後將位置指示器前進到下一個字元。

在內部,如果寫入指標 (pptr) 沒有可用的寫入位置,則函式會呼叫虛保護成員 overflow。否則,函式直接使用寫入指標 (pptr),而無需呼叫虛成員函式。

其行為等同於如下實現:
1
2
3
4
5
6
int sputc(char c) {
  if ( (!pptr()) || (pptr()==epptr()) ) return overflow(c);
  *pptr()=c;
  pbump(1);
  return c;
}

引數

c
要寫入的字元。

返回值

成功時,將寫入的字元作為 int 型別的值返回。
否則,它返回檔案結束值 (EOF) 來表示失敗。

示例

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;
}

此示例程式碼將每個字元寫入檔案,直到出現句點字元 (.)。

資料競爭

修改*流緩衝區*物件。
同時訪問同一*流緩衝區*物件可能會導致資料競爭。

異常安全

基本保證:如果丟擲異常,則流緩衝區處於有效狀態(這也適用於標準派生類)。

另見