string to a function

i had an exam of c++ .there was a question in it in whoch we had to write a programme in which i had to pass string to a function and it also had to return a srring so i wrote like this: string countrycode (string); // this was the declaration . is this format write i did it on my compiler and it runned
Yes that's correct. You could have also passed the string as a reference to the function, so nothing would have needed to be returned but I do not see the benefit of that method in this situation.
it was just to check to our skill ..my friend told me that a string could only pass through a function through a pointer ..is it right?
No, you don't have to pass a string as a pointer, but you may if you choose to. If you're passing a C-string you have to pass a pointer (because C-strings are char pointers.)
closed account (3qX21hU5)
No that is not right.

1
2
3
4
5
6
7
8
string countrycode (string str) {
    return str + ".";
}

int main () {
    string myStr= "This is my string with no punctuation";
    cout << countrycode(myStr) << endl;
}


or if you wanted to pass by reference, and not "return" anything but instead alter the info in the memory location of the original variable passed, use this:
1
2
3
4
5
6
7
8
9
10
void countrycode (string& myStr) {
	myStr = "This is my string WITH punctation.";
}

int main () {
    string myStr= "This is my string without punctuation";
	cout << myStr << endl;
    countrycode(myStr);
	cout << myStr << endl;
}


where myStr is the actual string you're passing to function countrycode
Last edited on
THanks i got it :)
The word string is ambiguous. It can denote either standard template class std::string or a character array. So I think your friend meant a character array. Though even character arrays can be passed by reference.
yes u are ryt .she must be talking about character array
Last edited on
Topic archived. No new replies allowed.