c++stringstream

Can someone explain to me briefly what is std::streampos?


Can you show me some examples with std::streampos? I am not sure what it is used for and I don't know how to work with it.

I saw in a project in github:

std::streampos pos = ss.tellg();

where ss is std::stringstream.

Why don't we use int pos = ss.tellg(), for example in this case?


Solution

  • Why don't we use int pos = ss.tellg(), for example in this case?

    Because std::streampos happens to be the type returned by std::basic_stringstream<char, std::char_traits<char>, std::allocator<char>>::tellg().

    Maybe on one computer it's something that converts cleanly to an int, but not on another. By using the correct type, your code is platform-independant.

    Also note that std::streampos is the type returned by the tellg() method of that very specific class, not the type returned by tellg() methods everywhere. Other streams might very well return a different type instead of std::streampos, and you should be accounting for that.

    The actual cleanest way to choose the correct type for pos is to literally ask the type: "What should I be using to represent positions in the stream?":

    std::stringstream::pos_type pos = ss.tellg();
    

    Or just use auto so you don't have to worry about it:

    auto pos = some_stream.tellg();