`std::swap` doesn't work as intended in string manipulation

Viewed 248

I have tried to make basic string encryption, by swapping two consecutive letters. And it didn't really work as I intended.

#include <iostream>
#include <string.h>
#include <algorithm>

int main() 
{
    std::string str = "This is a simple string.";
    for (int i = 0; i <= str.length(); i++) {
        std::swap(str[i], str[i + 1]);
    }
    std::cout << str;
    std::cin.get();
}

I want to actually swap two near letters, so it will look like encrypted. The Current result is

his is a simple string.
2 Answers

First of all, you have out of bound access because of

for (int i = 0; i <= str.length(); i++) 
//                ^^^^

hence the behavior of your program is undefined. You want to iterate one past the size of the string. In addition to that, loop only if the string is not empty(credits @jww).

Secondly, there is a comparison between int and unsigend int(i.e. str.length()) which is also not you want.

Last but not least, add the proper header for std::string(as @PaulMcKenzie pointed out in the comments).

Altogether, you probably want this

#include <string>

for (std::size_t i = 0; !str.empty() && i < str.size()-1; i += 2) {
//   ^^^^^^^^^^^        ^^^^^^^^^^^^        ^^^^^^^^^^^^   ^^^^^
    std::swap(str[i], str[i + 1]);
}

I think you were aiming for something like:

std::string str = "This is a simple string.";
for (int i = 0; i <= str.length()-2; i+=2) 
{
    std::swap(str[i], str[i + 1]);
}
std::cout << str;

with output

hTsii  s aispmels rtni.g
Related