C++字符串类中的sprintf函数

3

我非常喜欢sprintf in c++?中给出的答案,但它仍然不完全符合我的要求。

我想创建一个包含占位符的常量字符串,例如:

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

然后使用可替换参数构建字符串,例如:

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

但如果可以的话,我希望避免使用C字符串。

使用stringbuilder()方法需要将常量字符串分块,并在使用时进行组装。这是一种不错的方法,但我想做得更好。


url 的声明是什么? - John Dibling
好的,以上内容将是一个char[],但我想要能够生成C++字符串的东西。 - Thom
2个回答

11

Boost 格式库 似乎是你所需要的,例如:

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

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

或者对于你的具体示例:

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

1
刚刚我也在写同样的东西 :) - icabod
@icabod - 西部最快枪手问题 - Flexo
好的,我已经从http://www.boostpro.com/download/下载了boost 1.4.7并运行了安装程序。我正在查看文件,但没有找到格式库。我打开了文档,它们谈论了格式,但无法告诉我要使用哪个库。我需要在Visual C++下运行此程序,并使用来自www.madewithmarmalade.com的Marmalade在模拟器上进行后续部署到iPhone和Android。 - Thom
格式化库是头文件库之一。你只需确保将其头文件放在你的包含路径中,然后就可以使用它了。查看例如这个问题以获取有关在MSVC中使用boost的更多信息。 - Flexo
好的,我接受了(顺便说一下,这对我来说是个好消息),但是当我进入格式目录时,为什么我找不到format.hpp?我找到了format_class.hpp、format_fwd.hpp和format_implementation.hpp。 - Thom
我在Windows上不使用boost,也不太确定boostpro.com是什么,但我会从http://sourceforge.net/projects/boost/files/boost/1.47.0/获取它 - 无论如何,format.hpp不在format目录中,而是在顶层的“includes”目录中。 - Flexo

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接