swapping lettters in array

May 3, 2013 at 4:44am
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;
    
    
    
};
May 3, 2013 at 4:49am
temp1 = word[10];

why a 10 here ? This should be swap1 ?

What exactly doesn't work ?
May 3, 2013 at 5:17am
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);
}
May 3, 2013 at 8:18am
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?
May 3, 2013 at 8:19am
It doesn't print out the result at the end.
May 3, 2013 at 10:50am
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 May 3, 2013 at 10:51am
May 3, 2013 at 10:54am
You should print out 'word' not 'temp1'
Because your way it will always print out the last letter of the array.
Last edited on May 3, 2013 at 10:55am
Topic archived. No new replies allowed.