I expected this to be straightforward using a for loop with replace(str.begin(), str.end(), "x", "y") but instead "x" and "y" are a certain character in an array, so: replace(str.begin(), str.end(), arrX[1], arrY[1]) in the loop:
for (int i = 0; i < arraySize; i++) {
replace( str.begin(), str.end(), arrX[i], arrY[i]);
}
but in my code:
#include <iostream>
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
string Caesar(string str) {
char alph[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
string caesar = "abcdefghijklmnopqrstuvwxyz";
const int arraySize=sizeof(alph)/sizeof(alph[0]);
rotate(caesar.begin(), caesar.begin()+3, caesar.end());
for (int i = 0; i < arraySize; i++) {
replace(str.begin(), str.end(), alph[i], caesar[i]);
}
return str;
}
int main() {
cout << Caesar("hello");
}
caeser string is alph rotated by three.
Outputting caesar gives expected results. (abcdef... becomes xyzabc... when just printing caesar.)
My loop seems to be the thing messing it up, when given hello it produces ccaaa. I tested replacing one letter and it worked but it seems my for loop is what the problem is, but I can't seem to find out what is wrong.
UPDATE:
I found out a way to do it that supports non alphabetical characters using a while loop that checks if it is alphabetical and then goes through the alphabet comparing each letter to a letter in the string until they match and than replace that with the rotated Caesar alphabet, if they don't match it goes to the next one and when found it resets 'j' to 0 so it can do it again for the next letter by increment 'i' this time, if the char is not a letter it just increases 'i' to the next char to just skip over it until it reaches the new letter or the end of the string.
#include <iostream>
#include <algorithm>
using namespace std;
bool IsInArray(string array, char element) {
for(int i = 0; i < array.length(); i++){
if(array[i] == element){
break;
}
}
}
string rot(int n, string str) {
transform(str.begin(), str.end(), str.begin(), ::tolower);
string alph = "abcdefghijklmnopqrstuvwxyz";
string ciph = alph;
rotate(ciph.begin(), ciph.begin() + n, ciph.end());
int i = 0;
int j = 0;
while (i < str.length()) {
if (IsInArray(alph, str[i])) {
if (str[i] == alph[j]) {
str[i] = ciph[j];
i++;
j = 0;
}
else {
j++;
}
}
else {
i++;
}
}
return str;
}
int main() {
cout << rot(2, "This cipher works with more than just alpha chars!");
return 0;
}
char caesar[arraySize];This is not valid C++ syntax. Arrays must have compile-time bounds stated, not variable. ChangearraySizetoconst int arraySize=...; And why not just usestd::rotateinstead of yourleftRotatefunction, so that we are truly convinced "it works"?