#include <iostream>
#include <string>
using namespace std;
int main()
{
string a, b, temporary; // function to swap s and d (splendid day to dplendid say)
cout << "Input two words: " << endl;
cin >> a >> b;
cin.get(); //capture user input // to add index parameters?
temporary = a[0]; //assign temp variable to a[0]
b[0] = a[0]; //allocate b to a
b[0] = temporary; //do swap
swap(a[0], b[0]);
cout << "The two words you entered are: " << a << " " << b << endl; //attempt output
return 0;
}
First of all, you are only swapping the first character of the strings. a[0]
is the first character of a
, and likewise for b
.
Second, you are swapping twice: Once with std::swap
and once using three assignments and a temporary. Swapping twice puts it back the way it started!
temporary = a[0]; //assign temp variable to a[0]
b[0] = a[0]; //allocate b to a
b[0] = temporary; //do swap
swap(a[0], b[0]);