C++ streambuf::sungetc() 函式



C++ 的 std::streambuf::sungetc() 函式用於從輸入序列返回下一個字元,而不會推進流緩衝區的當前位置。

如果沒有可用的字元,它將返回 EOF(檔案結束)。

語法

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

int_type sungetc();

引數

它不接受任何引數。

返回值

它返回受控輸入序列的新當前字元的值,作為 int 型別的值。

異常

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

資料競爭

它修改流緩衝區物件。

示例 1

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

#include <iostream>
#include <sstream>
int main() {
   std::istringstream a("Car");
   char b;
   b = a.get();
   a.rdbuf() -> sungetc();
   b = a.get();
   std::cout << "Result : " << b << std::endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

Result : C

示例 2

考慮以下示例,我們將使用 sungetc() 函式,然後是 sgetc() 函式。

#include <iostream>
#include <sstream>
int main() {
   std::string x = "TP";
   std::stringbuf y(x);
   char x1 = y.sbumpc();
   std::cout << "Read character: " << x1 << std::endl;
   y.sungetc();
   char x2 = y.sgetc();
   std::cout << "After sungetc(), peeked character: " << x2 << std::endl;
   return 0;
}

輸出

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

Read character: T
After sungetc(), peeked character: T
streambuf.htm
廣告

© . All rights reserved.