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

后端 未结 3 1438

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:14

    The most C++-ish way to achieve sprintf-like functionality would be to use stringstreams.

    Here is an example based on your code:

    #include 
    
    // ...
    
    std::stringstream ss;
    std::vector tokens;
    ss << "Hello " << tokens.at(0) << " and " << tokens.at(1);
    
    std::cout << ss.str() << std::endl;
    

    Pretty handy, isn't it ?

    Of course, you get the full benefit of IOStream manipulation to replace the various sprintf flags, see here http://www.fredosaurus.com/notes-cpp/io/omanipulators.html for reference.

    A more complete example:

    #include 
    #include 
    #include 
    #include 
    
    int main() {
      std::stringstream s;
      s << "coucou " << std::setw(12) << 21 << " test";
    
      std::cout << s.str() << std::endl;
      return 0;
    }
    

    which prints:

    coucou           21 test
    

    Edit:

    As pointed by the OP, this way of doing things does not allow for variadic arguments, because there is no `template' string built beforehand allowing the stream to iterate over the vector and insert data according to placeholders.

提交回复
热议问题