0

I'm trying to swap my chars in the char array so they would look like this: KO KO KO KO KO, however, the output isn't quite as what I expected: K OK OK OK OK

Any clue on what I am doing wrong?

#include <string>
#include <iostream>
using namespace std;

void swapIt (char &char1, char &char2) {
    char temp;
    temp = char1;
    char1 = char2;
    char2 = temp;
}

int main() {
    char test[15] = "OK OK OK OK OK";
    int x;
    for (x = 0; x < 10; x++) {
        swapIt(test[x], test[x+1]);
    }
    cout << test;
}

So clueless right now.

3
  • 3
    Welcome to Stack Overflow! It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: How to debug small programs Commented Apr 20, 2016 at 18:38
  • 1
    Look at what you are doing. after first swap: KO OK OK OK OK, then K OOK OK OK OK, then K OKO OK OK OK...etc. Commented Apr 20, 2016 at 18:40
  • I remember when I first stumbled across the debugger bundled with turbo C way back in the stone ages. Man, stepping through programs line by line made finding the errors in my crap logic so easy. I wanted to throttle my CS professor for being such an ass that he'd never told us such things existed. Commented Apr 20, 2016 at 18:56

2 Answers 2

2

For x = 0, test[0] and test[1] are swapped. At this point, test = KO OK ...

For x = 1, test[1] and test[2] are swapped. At this point, test = K OOK ...

See the problem?

After a swap, x should be advanced by 3 places, not 1. I.e. x += 3 instead of x++.

Note also, that usage of the numbers 15 and 10 are arbitrary. Further, note that the character at x+1th position need to be within the bounds of the array. I would try

char test[] = "OK OK OK OK OK";
const int length = strlen(test);
for (int x = 0; x+1 < length; x += 3) {
    swapIt(test[x], test[x+1]);
}
cout << test;
Sign up to request clarification or add additional context in comments.

1 Comment

No, the position should be advanced by 3 places, there is also a space between words.
1

Every word consists of 3 chars 'O', 'K', ' '. After swapping the first two you have to move 3 chars forward.

Also the loop condition was incorrect - 10 instead of the string size - 15. The correct version is:

for (x = 0; x < 15; x+=3) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.