Quick probably obvious question.
If I have:
void print(string input) { cout << input << endl; }
How do I call it like so:
print("Yo!");
It complains that I'm passing in char *, instead of std::string. Is there a way to typecast it, in the call? Instead of:
string send = "Yo!"; print(send);
In C, if you need to amend a string in a called function, pass a pointer to the first char in the string as an argument to the function. If you have allocated storage for the string outside the function, which you cannot exceed within the function, it's probably a good idea to pass in the size.
To pass a string by value, the string pointer (the s field of the descriptor) is passed. When manipulating IDL strings: Called code should treat the information in the passed IDL_STRING descriptor and the string itself as read-only, and should not modify these values.
To pass a one dimensional string to a function as an argument we just write the name of the string array variable. In the following example we have a string array variable message and it is passed to the displayString function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With