Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

std - 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 to 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...