sprintf与C ++字符串类 [英] sprintf with C++ string class

查看:140
本文介绍了sprintf与C ++字符串类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢在 c ++中的sprintf 中给出的答案,但它仍然不是什么我正在寻找。

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

但我真的想远离C字符串如果我可以帮助它。

but I really want to stay away from C strings if I can help it.

stringbuilder()方法需要我组合我的常量字符串,并组装他们,当我想使用它们。这是一个好的方法,但我想做的是干净的。

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格式库听起来像您正在查找的内容,例如:

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

或者您的具体示例:

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

这篇关于sprintf与C ++字符串类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆