Toine H
Toine H

Reputation: 362

Print formatted string using a std::vector (of variable size)

I use the Magento 2 REST API and want to handle errors that get thrown in C++.

Example error response:

{
  "message": "Could not save category: %1",
  "parameters": [
    "URL key for specified store already exists."
  ]
}

I can retrieve both of these into a String and std::vector which leaves me with the question:

How am I able to return a String that is formatted by filling the placeholders?

With a fixed size, I could do something along the lines of this

char* buffer = new char[200];
String message = "Could not save category: %1";
std::vector<String> parameters = {"URL key for specified store already exists."};

String result = sprintf(buffer,message.c_str(),parameters[0]);

But, alas, I do not know the size beforehand.

How should I go about doing this? Are there stl functions that could help, should I be using self-written templates(no experience with this), can I convert the std::vector to a va_list, or are there other solutions?

Upvotes: 0

Views: 754

Answers (1)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39390

Edit: I didn't notice this asks for a C++ dialect and not Standard C++. Leaving it for now, might be of use for other people.


Nothing standard exists that will do that automatically. That being said, if your interpolation format is just %<number> it might be easy enough to write:

string message = "Could not save category: %1";
std::vector<string> parameters = {"URL key for specified store already exists."};

for (size_t i = 0; i < parameters.size(); ++i) {
    const auto interp = "%" + std::to_string(i+1);
    const size_t pos = message.find(interp);

    if (pos != std::string::npos)
        message.replace(pos, interp.size(), parameters[i]);
}

This will put the result in the message string. Of course this implementation is rather limited and not particularly efficient, but again, doing this properly requires a library-sized solution, not SO-answer-sized one.

live version.

Upvotes: 1

Related Questions