How can I format a std::string using a collection of arguments?

后端 未结 3 1436

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

Currently I am formatting the string this way:

string helloString = \"Hello         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 08:29

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

    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).

    Example:

    #include 
    #include 
    #include 
    #include 
    std::string format_range(const std::string& format_string, const std::vector& args)
    {
        boost::format f(format_string);
        for (std::vector::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 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.

提交回复
热议问题