Trey Taylor
Trey Taylor

Reputation: 103

Middle characters in string not being reversed - C++ (Reinvent)

Trying to just make a small string reverser and when reversing the characters of a string with an odd length return, only the first and last characters of the string seem to be getting swapped:

#include <iostream>

using namespace std;

int main()
{
    string word;
    cout << "Word: ";
    cin >> word;
    if (word.length() % 2 == 0)
    {
        for (int i = 0; i < (word.length()/2); i++)
        {
            swap(word[i], word[word.length() - i - 1]);
        }
    }
    else
    {
        for (int i = 0; i < (word.length()/2 - 1); i++)
        {
            swap(word[i], word[word.length() - i]);
        }
    }
    cout << word << endl;
}

Upvotes: 0

Views: 113

Answers (2)

5gon12eder
5gon12eder

Reputation: 25419

Your indexing logic is not correct. Look at this.

swap(word[i], word[word.length() - i]);

The loop starts with i == 0 sou you're trying to swap() characters at position i == 0 and word.length() - i == word.length() - 0 == word.length() which is out-of-bounds and therefore undefined behavior. You got that part right in the even case where you subtract 1.

Also consider what happens in the case that word.length() == 1. You check for

i < (word.length() / 2 - 1)

in the conditional of your for loop. If word.length() == 1, then word.length() / 2 == 0 and now you subtract 1 from it. This will underflow the (unsigned) integer, which is well-defined but gives you the most positive value so you'll loop over all kind of invalid indices.

In general, I think your case selection is needlessly complicated. It would be easier if you used iterators. Since you say this is an exercise for you, I won't show you the solution but you can easily find it in the web. This question gets asked here fairly often.

Upvotes: 2

user4580220
user4580220

Reputation:

Here is simple code:

#include <iostream>

using namespace std;

int main()
{
    string word;
    cout << "Word: ";
    cin >> word;
    for (int i = 0; i < (word.length()/2); i++)
    {
        swap(word[i], word[word.length() - i - 1]);
    }
    cout << word << endl;
}

you do not need if/else statement.

Upvotes: 2

Related Questions