c++ 凯撒加密


#include <iostream>
#include <fstream>
using namespace std;

int main(){
  ifstream iFile("MySong.txt");
  //get the length of the file
  iFile.seekg(0,ios::end);
  int nFileLen = iFile.tellg();
  iFile.seekg(0,ios::beg);
  //allocate memory
  char* str = new char[nFileLen+1];
  //read data as block
  iFile.read(str,nFileLen);//读取nFileLen个字节的数据并存储到str变量
  iFile.close();
  str[nFileLen]=0;
  int nCaesar = 3;//假设Caesar移位为3
  int n=0;//记录回车数目
  for(int i=0;i< nFileLen;i++){
    //不做任何处理,直接输出字符,看是否出现\r\n
    printf("%c",str[i]);
    //开始对字母进行加密,如果位移后大于'z'或'Z',则减去26
    if((str[i] > 'a') && (str[i] < 'z')){
      str[i] += nCaesar;
      if(str[i] > 'z'){
        str[i] -= 26;
      }
    }else if((str[i] > 'A') && (str[i] < 'Z')){
        str[i] += nCaesar;
        if(str[i] > 'Z'){
          str[i] -= 26;
        }
    }
  }
  
    ofstream oFile("mySong2.txt");
    oFile.write(str,nFileLen);
    oFile.close();
    delete[] str;
    return 0;
}


C++实现凯撒加密的过程如下: 1. 首先定义一个字符串变量,存储需要加密的明文。 2. 确定加密的偏移量,即将明文中每个字符的ASCII码值向后移动多少位。 3. 将明文中的每个字符按照偏移量进行移动,得到密文。 4. 输出密文。 下面是示例代码: ```c++ #include <iostream> #include <string> using namespace std; string caesarCipher(string plaintext, int offset) { string ciphertext = ""; for (int i = 0; i < plaintext.length(); i++) { if (isalpha(plaintext[i])) { if (isupper(plaintext[i])) { ciphertext += char(int(plaintext[i] + offset - 65) % 26 + 65); } else { ciphertext += char(int(plaintext[i] + offset - 97) % 26 + 97); } } else { ciphertext += plaintext[i]; } } return ciphertext; } int main() { string plaintext = "hello world"; int offset = 3; string ciphertext = caesarCipher(plaintext, offset); cout << "Plaintext: " << plaintext << endl; cout << "Ciphertext: " << ciphertext << endl; return 0; } ``` 在上面的代码中,`caesarCipher()`函数接受两个参数,分别是需要加密的明文和偏移量。该函数返回加密后的密文。在该函数中,首先遍历明文中的每个字符,如果该字符是字母,则进行加密;否则,直接将该字符添加到密文中。对于字母的加密,需要分别处理大写字母和小写字母,具体过程是将其ASCII码值向后移动偏移量个位置,并将结果转换为对应的字符。最后,将加密后的密文返回。 在`main()`函数中,我们定义了明文和偏移量,然后调用`caesarCipher()`函数进行加密,并输出加密后的密文。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值