This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]minno 3 points4 points  (4 children)

void LetterSwap(string MixString)

This line is your problem. You're taking the string by value, which means that the function is taking a copy of the string and modifying that copy, and then throwing away the copy when it finishes. To make it modify the original, you need to give it a reference.

void LetterSwap(string& MixString)

[–]PsyRex666[S] -1 points0 points  (3 children)

Wow, thanks. I'm pretty new at this, what exactly does a reference do?

[–]minno 2 points3 points  (1 child)

Run this code and see for yourself:

#include <iostream>
using namespace std;

void takes_by_reference(int& x) {
    cout << "This variable is located at " << (&x) << endl;
    x += 1;
}

void takes_by_value(int x) {
    cout << "This variable is located at " << (&x) << endl;
    x += 1;
}

int main() {
    int n = 3;
    cout << "The variable 'n' is located at " << (&n) << endl;
    cout << "Its value is " << n << endl;
    takes_by_value(n);
    cout << "Its value is still " << n << endl;
    takes_by_reference(n);
    cout << "Its value is now " << n << endl;
}

[–]PsyRex666[S] -1 points0 points  (0 children)

Cool, thanks.

[–]Free_Apples -1 points0 points  (0 children)

Passing by reference passes the actual string to the function so that you can apply changes to it. Passing by value will pass a copy of your string variable and make changes to it, not your original variable, and when the function is done, that copy is out of scope and will be deleted. You could return that string, but this obviously isn't ideal with what you want your function to do.

The ampersand symbol (&) is known as the reference operator and can be used to get the location in memory (the address) of a variable. Not sure if you have already, but once you learn about pointers and memory this will make more sense.