【发布时间】:2019-10-24 07:09:51
【问题描述】:
我试图通过交换两个连续的字母来进行基本的字符串加密。 而且它并没有真正按我的预期工作。
#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();
}
我实际上想交换两个相邻的字母,所以它看起来像加密的。 当前结果是
his is a simple string.
【问题讨论】:
-
未定义的行为,因为索引超出了
str的末尾(当i == str.length ()和i == str.length () - 1时)。 -
这:“ for (int i = 0; i
-
另外,
std::string的正确标头是<string>,而不是<string.h>。 -
更准确地说,这里是dangers of using the incorrect string header。您的程序无法在 Visual Studio 中编译。
标签: c++ algorithm loops encryption stdstring