Constructing std::string using << operator

爱⌒轻易说出口 提交于 2019-12-24 18:02:09

问题


If we want to construct a complex string, say like this: "I have 10 friends and 20 relations" (where 10 and 20 are values of some variables) we can do it like this:

std::ostringstream os;
os << "I have " << num_of_friends << " friends and " << num_of_relations << " relations";

std::string s = os.str();

But it is a bit too long. If in different methods in your code you need to construct compound strings many times you will have to always define an instance of std::ostringstream elsewhere.

Is there a shorter way of doing so just in one line?

I created some extra code for being able to do this:

struct OstringstreamWrapper
{
     std::ostringstream os;
};

std::string ostream2string(std::basic_ostream<char> &b)
{
     std::ostringstream os;
     os << b;
     return os.str();
}

#define CreateString(x) ostream2string(OstringstreamWrapper().os << x)

// Usage:
void foo(int num_of_friends, int num_of_relations)
{
     const std::string s = CreateString("I have " << num_of_friends << " and " << num_of_relations << " relations");
}

But maybe there is simpler way in C++ 11 or in Boost?


回答1:


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

template<typename T, typename... Ts>
std::string CreateString(T const& t, Ts const&... ts)
{
    using expand = char[];

    std::ostringstream oss;
    oss << std::boolalpha << t;
    (void)expand{'\0', (oss << ts, '\0')...};
    return oss.str();
}

void foo(int num_of_friends, int num_of_relations)
{
    std::string const s =
        CreateString("I have ", num_of_friends, " and ", num_of_relations, " relations");
    std::cout << s << std::endl;
}

int main()
{
    foo(10, 20);
}

Online Demo




回答2:


You could use Boost.Format:

#include <iostream>
#include <boost/format.hpp>

using boost::format;

int main()
{
    std::cout << boost::format("I have %1% friends and %2% relations")
        % num_of_friends % num_of_relations; 
}


来源:https://stackoverflow.com/questions/35012814/constructing-stdstring-using-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!