Reputation: 1791
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?
Upvotes: 0
Views: 71
Reputation: 7
You can use:
char ch = 'a';
foo(std::string(1, ch));
std::string has a "fill constructor" that creates a string with n copies (1 in the above example) of ch.
If you have a function:foo(std::string s) { std::cout << s << std::endl; }
it will print 'a' and this should answer what you have asked for to do it inside the parenthesis.
Upvotes: -1
Reputation: 180415
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));
Upvotes: 5