C++ compose string in one line to give as parameterAsk Question

问题:

In my program I have a program that takes a std::string as parameter. When I call this function I want to give it a large (about 5) composition of strings. Is there a native toString() function that can spit out strings#? Can it be done on one line?

What I want:

std::string a = "sometext";
std::string b = "someothertext";
somefunction(ToString(a+b+"text"));

回答1:


This works aswell:

std::string a = "sometext";
std::string b = "someothertext";
somefunction(a + b + "text");

回答2:


std::string already has a operator+ that will concatenate strings. If you have

void foo(std::string some_name) { code in here }

And you want to pass it a combination of a bunch of string you can just use

foo(some_string + another_string + "some text" + even_another_string);

If all of your strings that you want to pass a literal strings then you will either have to add the custom string literal to one of them or convert one to a string

foo("this is a string"s + "another string" + "some more text");
//or
foo(std::string("this is a string") + "another string" + "some more text");
标签: string
© 2014 TuiCode, Inc.