string to a function

Mar 13, 2013 at 1:36pm
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
Mar 13, 2013 at 2:22pm
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.
Mar 14, 2013 at 3:06pm
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?
Mar 14, 2013 at 3:11pm
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.)
Mar 14, 2013 at 3:11pm
closed account (3qX21hU5)
No that is not right.

Mar 14, 2013 at 4:24pm
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 Mar 14, 2013 at 4:34pm
Mar 17, 2013 at 12:56pm
THanks i got it :)
Mar 17, 2013 at 1:05pm
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.
Mar 27, 2013 at 8:39am
yes u are ryt .she must be talking about character array
Last edited on Mar 27, 2013 at 8:40am
Topic archived. No new replies allowed.