C++ streambuf::setbuf() 函式



C++ 的std::streambuf::setbuf()函式用於設定流緩衝區物件的緩衝區。此函式允許自定義用於輸入和輸出操作的緩衝區。它接受兩個引數;指向用作緩衝區的字元陣列的指標及其大小。

語法

以下是 std::streambuf::setbuf() 函式的語法。

streambuf* setbuf (char* s, streamsize n);

引數

  • s, n − 它表示派生類中重寫函式可能使用的引數。

返回值

此函式返回 this。

異常

如果丟擲異常,物件處於有效狀態。

資料競爭

如果 s 和 n 兩個引數都為零,則不會引入資料競爭。否則,未指定。

示例 1

讓我們看下面的例子,我們將為 std::cin 流設定 12 位元組的自定義緩衝區。

#include <iostream>
#include <streambuf>
#include <string>
int main() {
   char x[12];
   std::streambuf * y = std::cin.rdbuf();
   y -> pubsetbuf(x, sizeof(x));
   std::string input = "Welcome.";
   std::cout << "Input : " << input << std::endl;
   std::cout << "Buffer size: " << sizeof(x) << " bytes" << std::endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

Input : Welcome.
Buffer size: 12 bytes

示例 2

考慮下面的例子,我們將緩衝區設定為 null。

#include <iostream>
#include <streambuf>
int main() {
   std::streambuf * x = std::cout.rdbuf();
   x -> pubsetbuf(NULL, 0);
   std::cout << "Buffer disabled." << std::endl;
   return 0;
}

輸出

以下是以上程式碼的輸出:

Buffer disabled.
streambuf.htm
廣告
© . All rights reserved.