Reputation: 50
I've got a function which takes a string, let's call it
void print(std::string myString)
{
std::cout << myString;
}
I want to do something like
char myChar;
myChar = '{';
print("Error, unexpected char: " + myChar + "\n");
It doesn't work.
I tried something like
print(std::string("Error, unexpected char") + std::string(myChar) + std::string("\n) )
but then std::string(myChar) becomes whatever int the char represents, it's printed as an int and isn't printed as it's alphanumeric representation!
Upvotes: 2
Views: 2516
Reputation: 311088
The function should be declared like:
void print( const std::string &myString)
{
std::cout << myString;
}
and called like:
print( std::string( "Error, unexpected char: " ) + myChar + "\n");
As for your comment:
as a follow up, would it have been possible to pass an anonymous function returning a string as an argument to print()? Something like print( {return "hello world";}
then you can do this as it is shown in the demonstration program:
#include <iostream>
#include <string>
void f( std::string h() )
{
std::cout << h() << '\n';
}
int main()
{
f( []()->std::string { return "Hello World!"; } );
return 0;
}
Upvotes: 2
Reputation: 1416
If you are using C++14, you can do this:
using namespace std::literals;
char myChar;
myChar = '{';
print("Error, unexpected char: "s + myChar + "\n"s);
Upvotes: 2
Reputation: 18480
You can convert any one and concat.
You can use str.c_str()
to convert C++ string to C character array.
Or
Use std::string inbuilt constructor to convert C character array to C++ string.
Upvotes: 1