I am trying to xor a small string , it works . When I try to use the XORed string , I can't even compile it.
string str = "MyNameIsMila";
string str_xored = "2*&.8"'*"; //you can't escape this or the result be be different
//Enc:2*&.8"'*:
//Dec:MyNameIsMila:
I tried to escape the string , but then I have another result at the end. Any good direction for this ? Output after escaping:
//Enc:yamesila:
//Dec:2*&.8"'*:
Hoped to get MyNameIsMila back.
The function looks like :
string encryptDecrypt(string toEncrypt) {
char key = 'K'; //Any char will work
string output = toEncrypt;
for (int i = 0; i < toEncrypt.size(); i++)
output[i] = toEncrypt[i] ^ key;
return output;
}
I've 2 things to say:
1: The value of a string needs to be between 2 -> ""
string str_xored = 2*&.8"'*; //this is not a valid syntax = error
//valid
string str_xored = "2*&.8";
str += '"';
str += "'*";
2: In your case I would use iterators:
#include <iostream>
#include <string>
//please don't use "using namespace std;"
std::string encryptDecrypt(std::string toEncrypt) {
char key = 'K'; //Any char will work
std::string output = ""; //needs to be empty
for (auto i = toEncrypt.begin(); i != toEncrypt.end(); i++) {
output += *i ^ key; //*i holds the current character to see how
//an iterator works have a look at my link
}
return output;
}
int main() {
std::string str = encryptDecrypt("Hello...!");
std::cout << str << std::endl;
return 0;
}
Here have a look at the (string) iterator:
If you think iterators are too difficult then use your
for(int i = 0; i < str.size(); i++){
//CODE
}
for()-loop