std::string.resize() and std::string.length()

Posted by dreamlax on Stack Overflow See other posts from Stack Overflow or by dreamlax
Published on 2010-05-21T07:26:00Z Indexed on 2010/05/21 7:30 UTC
Read the original article Hit count: 272

I'm relatively new to C++ and I'm still getting to grips with the C++ Standard Library. To help transition from C, I want to format a std::string using printf-style formatters. I realise stringstream is a more type-safe approach, but I find myself finding printf-style much easier to read and deal with (at least, for the time being). This is my function:


using namespace std;

string formatStdString(const string &format, ...)
{
    va_list va;
    string output;
    size_t needed;
    size_t used;

    va_start(va, format);

    needed = vsnprintf(&output[0], 0, format.c_str(), va);
    output.resize(needed + 1); // for null terminator??

    used = vsnprintf(&output[0], output.capacity(), format.c_str(), va);
    // assert(used == needed);

    va_end(va);

    return output;
}

This works, kinda. A few things that I am not sure about are:

  1. Do I need to make room for a null terminator, or is this unnecessary?
  2. Is capacity() the right function to call here? I keep thinking length() would return 0 since the first character in the string is a '\0'.

Occasionally while writing this string's contents to a socket (using its c_str() and length()), I have null bytes popping up on the receiving end, which is causing a bit of grief, but they seem to appear inconsistently. If I don't use this function at all, no null bytes appear.

© Stack Overflow or respective owner

Related posts about c++

Related posts about c++-standard-library