如何使用参数集合格式化std :: string?

jil*_*t3d 15 c++ string-formatting variadic-functions stdstring

是否可以格式化std::string传递一组参数?

目前我正在以这种方式格式化字符串:

string helloString = "Hello %s and %s";
vector<string> tokens; //initialized vector of strings
const char* helloStringArr = helloString.c_str();
char output[1000];
sprintf_s(output, 1000, helloStringArr, tokens.at(0).c_str(), tokens.at(1).c_str());
Run Code Online (Sandbox Code Playgroud)

但是矢量的大小是在运行时确定的.是否有任何类似的函数sprintf_s采用参数集合并格式化std :: string/char*?我的开发环境是MS Visual C++ 2010 Express.

编辑: 我想实现类似的东西:

sprintf_s(output, 1000, helloStringArr, tokens);
Run Code Online (Sandbox Code Playgroud)

Sir*_*ius 12

大多数C++ - 实现sprintf类功能的方法是使用stringstreams.

以下是基于您的代码的示例:

#include <sstream>

// ...

std::stringstream ss;
std::vector<std::string> tokens;
ss << "Hello " << tokens.at(0) << " and " << tokens.at(1);

std::cout << ss.str() << std::endl;
Run Code Online (Sandbox Code Playgroud)

非常方便,不是吗?

当然,您可以充分利用IOStream操作来替换各种sprintf标志,请参阅http://www.fredosaurus.com/notes-cpp/io/omanipulators.html以供参考.

一个更完整的例子:

#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>

int main() {
  std::stringstream s;
  s << "coucou " << std::setw(12) << 21 << " test";

  std::cout << s.str() << std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

打印:

coucou           21 test
Run Code Online (Sandbox Code Playgroud)

编辑:

正如OP所指出的,这种做法不允许使用可变参数,因为事先没有构建"模板"字符串,允许流迭代向量并根据占位符插入数据.


vis*_*tor 9

您可以使用Boost.Format库来执行此操作,因为您可以逐个提供参数.

这实际上使您能够实现您的目标,与printf您必须立即传递所有参数的系列完全不同(即您需要手动访问容器中的每个项目).

例:

#include <boost/format.hpp>
#include <string>
#include <vector>
#include <iostream>
std::string format_range(const std::string& format_string, const std::vector<std::string>& args)
{
    boost::format f(format_string);
    for (std::vector<std::string>::const_iterator it = args.begin(); it != args.end(); ++it) {
        f % *it;
    }
    return f.str();
}

int main()
{
    std::string helloString = "Hello %s and %s";
    std::vector<std::string> args;
    args.push_back("Alice");
    args.push_back("Bob");
    std::cout << format_range(helloString, args) << '\n';
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里工作,模仿等.

请注意,如果向量不包含确切的参数量,它会抛出异常(请参阅文档).你需要决定如何处理这些.

  • 问题是要求 std::string 而不是 boost。 (2认同)