samedi 25 juillet 2015

C++ string append formated data

I have created my own string class in C++ (I didnt want to use 3rd party lib or std::string for some reasons).

Now I have an issue with appending formated string into my own. I have created this function:

void MyStringAnsi::AppendFormat(const char * str, ...)
{
    va_list vl;
    va_start(vl, str);

    int newLength = static_cast<int>(this->length + 10 * strlen(str));
    this->ResizeBuffer(this->length + newLength);

    vsnprintf_s(this->str + this->length, newLength, newLength, str, vl);

    va_end(vl);

    this->length = static_cast<int>(strlen(this->str));
    this->str[this->length] = '\0';
    this->hashCode = UINT32_MAX;
}

Problem is with newLength of appended string. I can not calculate it, so I set it by some "magic" multiplier, but it is not enough.

Is this problem solvable (iterate all varagrs or change it to mething else)? I can use C++11 features, so maybe something there?

I call my code with

MyStringAnsi str = "xy";
str.AppendFormat("%s AND %d", someLongString, -50.7);

Aucun commentaire:

Enregistrer un commentaire