swapping lettters in array

I have a function that is suppose to swap positions of 2 letters but It doesn't seem to work. Im passing in the array of char into the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void swapletter(char word[])
{
    char temp1;
    int swap1;
    int swap2;
    cout<<"What is the first location: ";
    cin>>swap1;
    
    cout<<"What is the second location: ";
    cin>>swap2;
    
    
    temp1 = word[10];
    word[swap1] = word[swap2];
    word[swap2] = temp1;
    
    cout<<"The result is: "<<temp1;
    
    
    
};
temp1 = word[10];

why a 10 here ? This should be swap1 ?

What exactly doesn't work ?
I suggest using std::string and std::swap_ranges. No need to reinvent the wheel, unless you insist.

1
2
3
4
5
void swap2(std::string &lhs, std::string &rhs, int lhsbeg, int rhsbeg)
{
    enum {AMOUNT_OF_LETTERS = 2};
    std::swap_ranges(lhs.begin() + lhsbeg, lhs.begin() + lhsbeg + AMOUNT_OF_LETTERS, rhs.begin() + rhsbeg);
}
temp1 = word[10];

word[10] is the length of the array, if i put in swap1 that just copies over the number of array into temp1 though?
It doesn't print out the result at the end.
You are trying to swap elements of the array? The idea you have for swapping is correct, but as writetonsharma pointed out, you should be doing:
temp1 = word[swap1]; // possibly swap1-1

> It doesn't print out the result at the end.

Line 17 is confusing. What result are you trying to achieve?
Last edited on
You should print out 'word' not 'temp1'
Because your way it will always print out the last letter of the array.
Last edited on
Topic archived. No new replies allowed.