我在创建使用用户输入的旋转数加密单词的函数时遇到了一些问题。这是我目前所拥有的:
string encryptWord(string word, int num)
{
string newWord;
newWord = word;
for(int i = 0; i < word.length(); i++)
{
newWord[i] = tolower(word[i]);
if((word[i] >= 'a') && (word[i] <= 'z'))
{
newWord[i] = word[i] + (num % 26);
if(newWord[i] > 'z')
newWord[i] = newWord[i] - 26;
}
}
return newWord;
}
当我测试它时,现在在我的 main 中
cout << encryptWord("xyz", 6);
我得到的输出是:de
同样,对于解密我有
string decryptRotWord(string word, int num)
{
string newWord;
num = num % 26;
int index;
for(int i = 0; i < word[i]; i++)
{
newWord[i] = tolower(word[i]);
if(word[i] >= 'a' && word[i] <= 'z')
{
index = word[i] - num;
if(index < 'a')
index = index + 26;
newWord[i] = index;
}
}
return newWord;
}
然而,对于这个,当我测试时它不输出任何东西
cout << decryptRotWord("vdds", 2);
最佳答案
在你的解密函数中,我认为你在循环结束条件上有错误:
for(int i = 0; i < word[i]; i++)
在加密函数中,你应该遍历长度
for(int i = 0; i < word.length(); i++)
关于c++旋转加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32753371/