开发者

sprintf with C++ string class

I really liked the answer given in sprintf in c++? but it still isn't quite what I'm 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 build the string with replaceable parameters like:

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

but I really want 开发者_如何学Goto stay away from C strings if I can help it.

The stringbuilder() approach requires me to chunk up my constant strings and assemble them when I want to use them. It's a good approach, but what I want to do is neater.


Boost format library sounds like what you are looking for, e.g.:

#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;
}


Take a look at: Boost Format

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜