C++ streambuf::sgetn() 函式



C++ 的std::streambuf::sgetn()函式用於從流緩衝區的輸入序列中提取指定數量的字元,並將它們儲存到提供的陣列中。

此函式最多讀取給定數量的字元,並相應地修改流緩衝區的內部位置。它返回成功提取的字元數。

語法

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

streamsize sgetn (char_type* s, streamsize n);

引數

  • s - 指向複製字元序列的陣列的指標。
  • n - 要檢索的最大字元數。

返回值

此函式返回複製的字元數。

異常

如果丟擲異常,則流緩衝區處於有效狀態。

資料競爭

它修改由 s 指向的陣列中前 n 個字元中的所有字元。

示例 1

在下面的示例中,我們將考慮 sgetn() 函式的基本用法。

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf a("Welcome");
   char b[6] = {
      0
   };
   a.sgetn(b, 5);
   std::cout << "Result : " << b << std::endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

Result : Welco

示例 2

考慮以下示例,我們將使用 pubseekpos() 和 sgetn() 函式。

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf a("ABCDE111223");
   char b[6] = {
      0
   };
   a.pubseekpos(4);
   a.sgetn(b, 4);
   std::cout << "Result : " << b << std::endl;
   return 0;
}

輸出

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

Result : E111
streambuf.htm
廣告

© . All rights reserved.