Consider a function
void foo(string s) {
...
}
I want to call the function as follows:
char ch = 'a';
foo(ch);
Of course it doesn't work as ch
is a char and we need to convert it into a string.
I know I can do
char ch = 'a';
string str;
foo(str ch);
I do not want to declare string str
beforehand, I want to do something during the function call itself to convert ch
into string
, like:
char ch = 'a';
foo(some_operation_on_ch);
Is it possible to do so, if yes, how?
CodePudding user response:
std::string
has a constructor that takes a character and an integer for the number of times you what the character repeated. Using that you could do
foo(std::string(1, ch));
The class also has a constructor that takes c-style string and a integer denoting the number of characters to copy and you can use that constructor like
foo(std::string(&ch, 1));
CodePudding user response:
You can use:
char ch = 'a';
foo(std::string(1, ch));