I’m writing a program that solves Caesar ciphers in C++. It takes a string of the alphabet and shifts it to the left each loop: “abc….yz” –> “bcd…..yza”. The problem is after another loop it goes: “bcd…..yza” –> “cde…..yzaa”.
char temp; // holds the first character of string
string letters = "abcdefghijklmnopqrstuvwxyz";
while (true)
{
temp = letters[0];
for (int i = 0; i < 26; i++)
{
if (i == 25)
{
letters += temp;
}
letters[i] = letters[i + 1];
cout << letters[i];
}
cin.get();
}
Copy and paste that code and you’ll see what I’m talking about. How do I fix this mysterious problem?
I think you need letters to be 27 characters, not 26, and instead of
letters += temp(which grows the string every time), useletters[26] = temp[0].…at which point you can just ditch
tempentirely:[edit]
Although the more natural way to handle this is to use arithmetic on the characters themselves. The expression
'a' + ((c - 'a' + n) % 26)will shift a charcbynplaces Caesar-style.