Search code examples
arraysstringindexingcharswap

Hi everyone, I`m sitting with a simple swap issue in C++ (two strings). I cant get my swap to work.My output is only "splendid day"


#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;
}

Solution

  • 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!

    swap once

    temporary = a[0]; //assign temp variable to a[0]
    b[0] = a[0];  //allocate b to a
    b[0] = temporary;  //do swap
    

    swap again

    swap(a[0], b[0]);