如何使用一组参数格式化std :: string? [英] How can I format a std::string using a collection of arguments?

查看:66
本文介绍了如何使用一组参数格式化std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过一组参数来格式化 std :: string ?

Is it possible to format std::string passing a set of arguments?

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

Currently I am formatting the string this way:

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.

But the size of the vector is determined at runtime. Is there any similar function to sprintf_s which takes a collection of arguments and formats a std::string/char*? My development environment is MS Visual C++ 2010 Express.

我想实现类似的目标:

I would like to achieve something similar:

sprintf_s(output, 1000, helloStringArr, tokens);

推荐答案

您可以使用

You can do it with the Boost.Format library, because you can feed the arguments one by one.

实际上,这使您可以实现自己的目标,与 printf 系列不同,在该系列中,您必须一次传递所有参数(即,您需要手动访问容器中的每个项目).

This actually enables you to achieve your goal, quite unlike the printf family where you have to pass all the arguments at once (i.e you'll need to manually access each item in the container).

示例:

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

您可以在这里工作,使其成为模板等.

You can work from here, make it templated etc.

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

Note that it throws exceptions (consult documentation) if the vector doesn't contain the exact amount of arguments. You'll need to decide how to handle those.

这篇关于如何使用一组参数格式化std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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