Home > OS >  Can I throwaway the last character of a std::stringstream?
Can I throwaway the last character of a std::stringstream?

Time:01-07

This is basically what I want to do.

int main(int argc, char* argv[])
{
    std::stringstream ss;
    ss << "12345";
    ss.seekp(-1, std::ios::end);
    ss << '\0';
    assert(ss.str() == "1234");     // nope!
    return 0;
}

This question seems like a duplicate, but the answer is about writing a sequence of tokens and not actually addresses the original question.

CodePudding user response:

The best I can think of is

std::string contents = std::move(ss).str();
contents.resize(contents.size() - 1); // assumes size() > 0 !!
ss.str(std::move(contents));

Note that this is distinct from the solution in the comments: judicious choice of functions and overloads should avoid reallocating the buffer and copying the contents. (ss.str() would be a copy, contents.substr(...) would be a copy, and ss.str(contents) would be a copy.) Note that this requires C 20, and e.g. Clang's libc doesn't seem updated yet.

  • Related