Reputation: 13
I'm just learning programming in c++. In my homework I need to compare three strings given by the user by a prompt. I know that for a function to modify certain values directly instead of returning a value I need to use pointers. I also know that strings already behave like pointers. This is my code so far but I don't know where I'm wrong:
#include"std_lib_facilities.h"
void switching (string x, string y){
string flag;
if (x>y){flag=y;
y=x;
x=flag;
}
}
int main(){
string s1, s2, s3;
cout<<"introduce three words: ";
cin>>s1>>s2>>s3;
switching(s1,s2);
cout<<s1<<" "<<s2<<" "<<s3;
cout<<endl;
switching(s2,s3);
cout<<s1<<" "<<s2<<" "<<s3;
cout<<endl;
switching(s1,s2);
cout<<s1<<" "<<s2<<" "<<s3;
cout<<endl;
return 0;
}
Upvotes: 0
Views: 8615
Reputation: 155363
Your function is receiving the strings by value (copies), not by reference (or pointer), so it can't actually perform the swap you're trying to do. Receive the parameters by reference instead by changing the prototype to:
void switching (string& x, string& y){
For the record, while string
s wrap pointers to char
arrays, they behave like values, not pointers; if you receive them by value, they will allocate a new block of memory and copy the complete contents of the string into it. That's why you want reference semantics if at all possible; otherwise, you're making a lot of needless copies. You might be thinking of C style string literals and char
arrays, which do get passed around as pointers to their first character, but that doesn't apply to true C++ std::string
s.
You can also avoid the explicit temporary flag
object using std::swap
from <utility>
(<algorithm>
if you're not on C++11, but you really should be on C++11 by now; writing pre-C++11 C++ is just needlessly masochistic at this point):
void switching (string& x, string& y){
if (x>y) std::swap(x, y);
}
Upvotes: 3