Sprintf with C ++ String Class

I really liked the answer in sprintf in C ++? but he is still not quite what I am looking for.

I want to create a constant string with placeholders like

const std::string LOGIN_URL = "%s://%s/chronicle/spring/api/logout";

and then create a string with removable parameters, for example:

sprintf(url, LOGIN_URL, protocol, server); //coding sprintf from long ago memory, please ignore

but I really want to stay away from C lines if I can help.

The stringbuilder () method requires me to break my constant lines and collect them when I want to use them. This is a good approach, but what I want to do is more neat.

+3
source share
2 answers

The acceleration format library sounds like you're looking, for example:

#include <iostream>
#include <boost/format.hpp>

int main() {
  int x = 5;
  boost::format formatter("%+5d");
  std::cout << formatter % x << std::endl;
}

Or for your specific example:

#include <iostream>
#include <string>
#include <boost/format.hpp>

int main() {
  const std::string LOGIN_URL = "%s://%s/chronicle/spring/api/logout";

  const std::string protocol = "http";
  const std::string server = "localhost";

  boost::format formatter(LOGIN_URL);
  std::string url = str(formatter % protocol % server);
  std::cout << url << std::endl;
}
+11
source

:

+1

Source: https://habr.com/ru/post/1622529/


All Articles