I'm working on a Caesar Shift Cipher for my school assignment and am having trouble implementing the ASCII wrap around functionality. The problem is when the shift occurs outsize of the ASCII range [0, 127]. I currently % the result of the shift by 128 which essentially wraps around the ASCII table. However, values 0-31 are control characters and are not being stored correctly in the string. This prevents me from being able to decrypt the string. Is there a specific data structure that I should use to preserve all of the characters in the ASCII table?
Here is my code:
std::string shift(const std::string& str) {
int shift_pos = 9;
char original_str[str.length()];
char encrypted_str[str.length()];
std::strcpy(original_str, str.c_str());
for (int i = 0; i < str.length(); i++) {
encrypted_str[i] = (original_str[i] + shift_pos) % 128;
}
return encrypted_str;
}
You have two bugs in your code:
std::strcpy(original_str, str.c_str());
The strcpy
function is for C-style strings. Use memcpy
here.
return encrypted_str;
How is the constructor for std::string
invoked by this return
statement supposed to know how long the string is? The std::string
constructor that takes a char *
is only for C-style strings. Call the constructor explicitly and pass the length to it.
If you fix those two issues, your strings should be able to properly handle any kind of arbitrary junk you want to store in them. Don't use any functions meant for C-style strings with arbitrary data.