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.

2
  • What is the declaration for url? Commented Sep 28, 2011 at 13:33
  • well, above, it would be a char[], but I want something that will generate a C++ string. Commented Sep 28, 2011 at 13:45

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

6 Comments

Was just writing the same thing myself :)
OK, I have downloaded boost 1.4.7 from 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.
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 for more on using boost with MSVC.
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.
|
1

Take a look at: Boost Format

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.