17

是否可以格式化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());

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

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

sprintf_s(output, 1000, helloStringArr, tokens);
4

3 回答 3

13

实现类似 sprintf 的功能的最 C++-ish 方法是使用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;

很方便,不是吗?

当然,您可以充分利用 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;
}

打印:

coucou           21 test

编辑

正如 OP 所指出的,这种做事方式不允许可变参数,因为没有预先构建的“模板”字符串允许流迭代向量并根据占位符插入数据。

于 2011-02-22T10:07:55.790 回答
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';
}

您可以从这里开始工作,使其模板化等。

请注意,如果向量不包含确切数量的参数,它会引发异常(查阅文档)。您需要决定如何处理这些问题。

于 2011-02-22T14:19:14.873 回答
1

如果您想避免手动处理输出缓冲区,boost::format 库可能会很有趣

至于将纯向量作为输入,如果 ,您希望发生tokens.size()<2什么?在任何情况下,您都不必确保向量足够大以索引元素 0 和 1 吗?

于 2011-02-22T10:11:22.110 回答