3

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.

Community
  • 1
  • 1
Thom
  • 14,013
  • 25
  • 105
  • 185

2 Answers2

11

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;
}
Flexo
  • 87,323
  • 22
  • 191
  • 272
  • 1
    Was just writing the same thing myself :) – icabod Sep 28 '11 at 13:32
  • @icabod - [fastest gun in the west](http://meta.stackexchange.com/questions/9731/fastest-gun-in-the-west-problem) – Flexo Sep 28 '11 at 13:35
  • OK, I have downloaded boost 1.4.7 from http://www.boostpro.com/download/ and ran the installer. I am looking through the files and there is no format lib. I opened the docs and they talk about format but can't get it to tell me which library to use. I need to run this under Visual C++ with an emulator with later deployment to iPhone and Android using Marmalade from www.madewithmarmalade.com. – Thom Sep 28 '11 at 14:42
  • Format library is one of the header file only libraries. You just need to make sure the header files for it are on your include path and then you're good to go. See for example [this question](http://stackoverflow.com/questions/2629421/how-to-use-boost-in-visual-studio-2010) for more on using boost with MSVC. – Flexo Sep 28 '11 at 15:00
  • OK, I'll buy that (good news for me by the way), but then when I go into the format directory, why do I not find a format.hpp? I find format_class.hpp, format_fwd.hpp, format_implementation.hpp. – Thom Sep 28 '11 at 15:08
  • I don't use boost on windows and I'm Not sure quite what boostpro.com is, but I'd just get it from http://sourceforge.net/projects/boost/files/boost/1.47.0/ - anyway format.hpp doesn't live in the format directory, it lives in the top level "includes" directory. – Flexo Sep 28 '11 at 15:13
1

Take a look at: Boost Format

doron
  • 27,972
  • 12
  • 65
  • 103