c++旋转加密

标签 c++ encryption caesar-cipher

我在创建使用用户输入的旋转数加密单词的函数时遇到了一些问题。这是我目前所拥有的:

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/

相关文章:

c++ - 将参数传递给方法时内联初始化整数数组

iphone - iPhone : Core Data or Property Lists? 上什么更容易加密

c++ - 如何在凯撒密码破译作业中使用英语字母频率?

c - 将每个字母移动多个位置后,如何按字母顺序将 z 换成 a,将 Z 换成 A?

C 中的凯撒密码向二维字符串数组添加额外的字符

c++ - 链接器阶段 : undefined reference

c++ - 医疗 3D 规划软件的最佳技术

c++ - 如何将 QObbject (QPushButton) 连接到其他类的方法?

winforms - 加密将重新分发的 App.config 文件中的部分和/或设置

c++ - 优化标准迭代算法