std::basic_...buf::sungetc(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

hey bestie πŸ’– you’ve landed on the std::basic_...buf::sungetc(3) page from the C++ Standard Libary manual (yes, that’s the header’s spelling, no cap πŸ’€). this is the C++ Standard Library function std::basic_streambuf::sungetc, and she’s here to put one character back like it’s nothing. periodt. πŸŽ€

✨ NAME ✨

std::basic_streambuf::sungetc β€” yep, that’s her. the member function that handles the one-character putback situation. iconic behavior only. πŸ’…

🌸 Synopsis 🌸

int_type sungetc();

okay so here’s the actual tea β˜•: if a putback position is available in the get area β€” and the vibe check is gptr() > eback() β€” then it decrements the next pointer (gptr()) and returns the character it now points to. slay. ✨

if a putback position is not available, then it calls pbackfail() to back up the input sequence if possible. fingers crossed, bestie 🫢

and fun fact: the I/O stream function basic_istream::unget is implemented in terms of this function. so yeah, she’s the blueprint. πŸ‘‘

πŸ’… Parameters πŸ’…

(none) β€” literally no parameters. not a single argument. she’s low-maintenance like that. πŸ™ˆ

πŸ”₯ Return value πŸ”₯

  • if a putback position was available: returns the character that the next pointer is now pointing at, converted to int_type with Traits::to_int_type(*gptr()). the next single-character input from this streambuf will return this character. so you literally get that same char next time. iconic. πŸ’–
  • if a putback position was not available: returns what pbackfail() returns, which is Traits::eof() on failure. sad girl hours if that happens 😭.

πŸ¦‹ Example πŸ¦‹

        // Run this code

        #include <iostream>
        #include <sstream>

        int main()
        {
            std::stringstream s("abcdef"); // gptr() points to 'a'
            char c1 = s.get(); // c = 'a', gptr() now points to 'b'
            char c2 = s.rdbuf()->sungetc(); // same as s.unget(): gptr() points
       to 'a' again
            char c3 = s.get(); // c3 = 'a', gptr() now points to 'b'
            char c4 = s.get(); // c4 = 'b', gptr() now points to 'c'
            std::cout << c1 << c2 << c3 << c4 << '\n';

            s.rdbuf()->sungetc();  // back to 'b'
            s.rdbuf()->sungetc();  // back to 'a'
            int eof = s.rdbuf()->sungetc();  // nothing to unget: pbackfail()
       fails
            if (eof == EOF)
                    std::cout << "Nothing to unget after 'a'\n";
        }

πŸ’€ Output πŸ’€

aaab
Nothing to unget after 'a'

πŸ‘€ See also πŸ‘€

  • sputbackc β€” puts one character back in the input sequence (public member function).
  • unget β€” unextracts a character (public member function of std::basic_istream<CharT,Traits>).

mwah πŸ’‹ source: http://cppreference.com Β· version/date: 2024.06.10 Β· page: std::basic_...buf::sungetc(3). now go unget responsibly, bestie πŸŒˆπŸ‘‘βœ¨

πŸ“¦ where this page comes from