Hi, I'm having problems with pointers, I want to make a function that swaps the value of one variable in Main() for another. I have it working within the function, but not back in Main(). Here's what I have so far;
#include <iostream>
#include <string>
usingnamespace std;
void swapS(string first, string second);
int main()
{
string alpha = "\"This starts the sentence\"", omega = " \"and this is the end\"";
int wait(0);
cout<<"The original statement;"<<endl;
cout << alpha <<omega<<endl<<endl;
swapS(alpha, omega);
cout<<"Now after running SwapS and back in main"<<endl;
cout << alpha <<omega<<endl<<endl;
cin>>wait;
return 0;
}
void swapS(string first, string second)
{
cout<<"this is what happens in swapS before swap;"<<endl;
cout<<first<<" "<<second<<endl<<endl;
string *pfirst = &first, *psecond = &second;
string hold = first;
*pfirst = *psecond;
*psecond = hold;
cout<<"this is what happens in swapS after swap;"<<endl;
cout<<first<<" "<<second<<endl<<endl;
}
So this is the only way I could think of solving it, by inputting the addresses of the variables into the swapS() function. But the added work of creating pointers to input them all just to do a quick swap kind of ruins the convenience. does anyone know how to make a swap function so that you only have to input the variable itself?
#include <iostream>
#include <string>
usingnamespace std;
void swapS(string *pfirst, string *psecond);
int main()
{
string alpha = "\"This starts the sentence\"", omega = " \"and this is the end\"";
string *palpha = &alpha, *pomega = ω
int wait(0);
cout<<"The original statement;"<<endl;
cout << alpha <<omega<<endl<<endl;
swapS(palpha, pomega);
cout<<"Now after running SwapS and back in main"<<endl;
cout << alpha <<omega<<endl<<endl;
cin>>wait;
return 0;
}
void swapS(string *pfirst, string *psecond)
{
cout<<"this is what happens in swapS before swap;"<<endl;
cout<<pfirst<<" "<<psecond<<endl<<endl;
string hold = *pfirst;
*pfirst = *psecond;
*psecond = hold;
cout<<"this is what happens in swapS after swap;"<<endl;
cout<<pfirst<<" "<<psecond<<endl<<endl;
}