Quick probably obvious question.
If I have:
void print(string input)
{
cout << input << endl;
}
How do I call it like
Make it so that your function accepts a const std::string&
instead of by-value. Not only does this avoid the copy and is therefore always preferable when accepting strings into functions, but it also enables the compiler to construct a temporary std::string
from the char[]
that you're giving it. :)
print(string ("Yo!"));
You need to make a (temporary) std::string
object out of it.
Not very technical answer but just letting you know.
For easy stuff like printing you can define a sort of function in your preprocessors like
#define print(x) cout << x << endl
You can write your function to take a const std::string&
:
void print(const std::string& input)
{
cout << input << endl;
}
or a const char*
:
void print(const char* input)
{
cout << input << endl;
}
Both ways allow you to call it like this:
print("Hello World!\n"); // A temporary is made
std::string someString = //...
print(someString); // No temporary is made
The second version does require c_str()
to be called for std::string
s:
print("Hello World!\n"); // No temporary is made
std::string someString = //...
print(someString.c_str()); // No temporary is made
Well, std::string
is a class, const char *
is a pointer. Those are two different things. It's easy to get from string
to a pointer (since it typically contains one that it can just return), but for the other way, you need to create an object of type std::string
.
My recommendation: Functions that take constant strings and don't modify them should always take const char *
as an argument. That way, they will always work - with string literals as well as with std::string
(via an implicit c_str()
).
Just cast it as a const char *. print((const char *)"Yo!") will work fine.