[英]Printing out an unswapped array
I'm learning how to make myself a simple XOR encryption. 我正在学习如何使自己成为简单的XOR加密。 However, to make things more difficult for a person to decipher the message I want to try to swap characters and then swap them back (after the user enters the key for the decryption).
但是,为了使人难以理解消息,我想尝试交换字符,然后再交换回来(在用户输入用于解密的密钥之后)。
This is my output: 这是我的输出:
yet ih ssia t se!t !
ey this is a test!!
Does anyone know why it is cutting off the h
in the second printout? 有谁知道为什么它会在第二次打印输出中截断
h
? I'm still fairly new to programming and spent a good hour trying to figure it out. 我对编程还很陌生,花了一个小时尝试解决这个问题。
Here is my code: 这是我的代码:
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
void doSwap (char &string1, char &string2) {
char temp;
temp = string1;
string1 = string2;
string2 = temp;
}
int main() {
string content = "hey this is a test!!";
string after, after2;
int i;
for (i = 0; i < content.size(); i+=2) {
doSwap(content[i], content[i+2]);
}
after = content;
cout << after << "\n";
for (i = after.size(); i > 0; i -=2) {
doSwap(after[i], after[i-2]);
}
after2 = after;
cout << after2 << "\n";
}
Your loop indexing is not correct. 您的循环索引不正确。 As @tadman pointed out, you will walk off the string.
正如@tadman所指出的那样,您将离开字符串。
The first loop would have to terminate 2 indices shorter than the size, so that when you add 2, it would be 1 less than content.size(). 第一个循环必须终止短于size的2个索引,因此当您添加2时,它将比content.size()小1。 Remember C/C++ is 0 indexed, therefore if size is 10, element 9 is the last index of the string.
请记住,C / C ++的索引为0,因此,如果大小为10,则元素9是字符串的最后一个索引。
for (i = 0; i < content.size()-2; i+=2) {
doSwap(content[i], content[i+2]);
}
Similarly the second loop should start 1 short of the size and terminate at 2, so when you index into i-2
, you are indexing no less than 0. 同样,第二个循环应以小于大小的1开始并以2结束,因此当您索引到
i-2
,您所索引的索引不少于0。
for (i = after.size()-1; i >= 2; i -=2) {
doSwap(after[i], after[i-2]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.