std::basic_streambuf<CharT,Traits>::sungetc

出自cppreference.com
< cpp‎ | io‎ | basic streambuf
 
 
 
 
int_type sungetc();

若回放位置在獲取區中可用(gptr() > eback()),則減少下一位置指針(gptr())並返回它現在指向的字符。

若回放位置不可用,則調用 pbackfail() 以在可能的情況下後備輸入序列。

I/O 流函數 basic_istream::unget 以此函數實現。

目錄

[編輯] 參數

(無)

[編輯] 返回值

若回放位置可用,則返回下一位置指針現在指向的字符,以 Traits::to_int_type(*gptr()) 轉換為 int_type。來自此 streambuf 的下個單字符輸入將返回此字符。

若回放位置不可用,則返回 pbackfail() 所返回者,在失敗時為 Traits::eof()

[編輯] 示例

#include <iostream>
#include <sstream>
 
int main()
{
    std::stringstream s("abcdef"); // gptr() 指向 'a'
    char c1 = s.get(); // c = 'a', gptr() 现在指向 'b' 
    char c2 = s.rdbuf()->sungetc(); // 同 s.unget() : gptr() 又指向 'a'
    char c3 = s.get(); // c3 = 'a' , gptr() 现在指向 'b'
    char c4 = s.get(); // c4 = 'b' , gptr() 现在指向 'c'
    std::cout << c1 << c2 << c3 << c4 << '\n';
 
    s.rdbuf()->sungetc();  // 回到 'b'
    s.rdbuf()->sungetc();  // 回到 'a'
    int eof = s.rdbuf()->sungetc();  // 无内容可反获取: pbackfail() 失败
    if (eof == EOF)
            std::cout << "Nothing to unget after 'a'\n";
}

輸出:

aaab
Nothing to unget after 'a'

[編輯] 參閱

在輸入序列中放回一個字符
(公開成員函數) [編輯]
撤銷上一個字符的提取
(std::basic_istream<CharT,Traits> 的公開成員函數) [編輯]