C++ 字符串中的中间字符未反转-C++;(重新发明)

C++ 字符串中的中间字符未反转-C++;(重新发明),c++,string,C++,String,尝试创建一个小字符串反转器,当使用奇数长度返回值反转字符串的字符时,似乎只有字符串的第一个和最后一个字符被交换: #include <iostream> using namespace std; int main() { string word; cout << "Word: "; cin >> word; if (word.length() % 2 == 0) { for (int i = 0; i

尝试创建一个小字符串反转器,当使用奇数长度返回值反转字符串的字符时,似乎只有字符串的第一个和最后一个字符被交换:

#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;
}
#包括
使用名称空间std;
int main()
{
字符串字;
cout>单词;
if(word.length()%2==0)
{
for(int i=0;i<(word.length()/2);i++)
{
交换(字[i],字[word.length()-i-1]);
}
}
其他的
{
对于(int i=0;i<(word.length()/2-1);i++)
{
交换(字[i],字[word.length()-i]);
}
}
cout下面是简单的代码:

#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;
}
#包括
使用名称空间std;
int main()
{
字符串字;
cout>单词;
for(int i=0;i<(word.length()/2);i++)
{
交换(字[i],字[word.length()-i-1]);
}
cout下面是简单的代码:

#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;
}
#包括
使用名称空间std;
int main()
{
字符串字;
cout>单词;
for(int i=0;i<(word.length()/2);i++)
{
交换(字[i],字[word.length()-i-1]);
}

cout你的索引逻辑不正确。看看这个

swap(word[i], word[word.length() - i]);
循环以
i==0
sou开始,您试图
swap()
位置的字符
i==0
word.length()-i==word.length()-0==word.length()
,这是越界的,因此是未定义的行为。在减去1的偶数情况下,这一部分是正确的

还考虑在<代码> Word.LoTHOST(=)1 的情况下发生的情况。检查< /P>

i < (word.length() / 2 - 1)
i<(word.length()/2-1)
for
循环的条件中。如果
word.length()==1
,则
word.length()/2==0
,现在从中减去1。这将使(
无符号
)整数下溢,该整数定义良好,但为您提供了最正值,因此您将循环所有类型的无效索引


一般来说,我认为你的案例选择是不必要的复杂。如果你使用迭代器会更容易。因为你说这是一个练习,所以我不会向你展示解决方案,但你可以很容易地在web上找到它。这个问题在这里经常被问到。

你的索引逻辑不正确。看看这个

swap(word[i], word[word.length() - i]);
循环以
i==0
sou开始,您试图
swap()
位置的字符
i==0
word.length()-i==word.length()-0==word.length()
,这是越界的,因此是未定义的行为。在减去1的偶数情况下,这一部分是正确的

还考虑在<代码> Word.LoTHOST(=)1 的情况下发生的情况。检查< /P>

i < (word.length() / 2 - 1)
i<(word.length()/2-1)
for
循环的条件中。如果
word.length()==1
,则
word.length()/2==0
,现在从中减去1。这将使(
无符号
)整数下溢,该整数定义良好,但为您提供了最正值,因此您将循环所有类型的无效索引


一般来说,我认为你的案例选择是不必要的复杂。如果你使用迭代器会更容易。因为你说这是一个练习,我不会向你展示解决方案,但你可以很容易地在web上找到它。这个问题在这里经常被问到。

你可以通过std::reverse()反转字符串我知道我只是想手动进行练习。你的问题是什么?你是否使用调试器逐步检查了代码?@Verman代码不好。在
else
案例中至少存在缓冲区溢出。你可以通过std::reverse()反转字符串我知道我只是想手动进行练习。你的问题是什么?你是否使用调试器逐步检查了代码?@Verman代码不好。在
else
案例中至少存在缓冲区溢出。