Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pass A String

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); 
like image 359
Josh Avatar asked Dec 17 '10 23:12

Josh


People also ask

Can you pass a string in C?

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.

How do you pass strings?

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.

Can you pass a string into a function?

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.


1 Answers

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::strings:

print("Hello World!\n"); // No temporary is made std::string someString = //... print(someString.c_str()); // No temporary is made 
like image 142
In silico Avatar answered Oct 01 '22 11:10

In silico