替换密码加密 [英] Encryption with substitution cipher

查看:53
本文介绍了替换密码加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要用另一个字母替换每个字母.例如,每个"a"被替换为"Q",每个"b"被替换为"W".我已经写了代码来加密下面的句子.

I am replacing each letter of the alphabet with another letter of the alphabet. For example, each 'a' gets replaced with a 'Q', and every 'b' gets replaced with a 'W'. I have written code to encrypt the sentence bellow.

#include<iostream>
#include<string>
#include<cctype>

using namespace std;

int main(){

    string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
    string key      {"QWERTYUIOPasdfghjklZXCVBNMqwertyuiopASDFGHJKLzxcvbnm"};

    string original {};
    string encrypted {};

    cout<<"Enter your secret message: ";
    getline(cin ,original);
    // cout<<"Encrypting message..."<<endl;

    for(int i=0;i<original.length();i++){
        if(isalpha(original.at(i)) == 1){
            encrypted.at(i) =  key.at(alphabet.find(original.at(i)));
        }
        else
            encrypted.at(i) = original.at(i);
    }

    cout<<"Encrypted message: "<<encrypted<<endl;
}

我正在用键中具有相同索引的char更改字符串字母中具有索引i的每个char.例如:-如果原始字符串="Hello"加密的字符串应为"iTssg"

I am changing each char with index i in string alphabets with char of the same index from key. For example:- If Original string = "Hello" encrypted string should be "iTssg"

但是当我运行该程序时,我得到了一个错误

But when i run this program i am getting an error

输出:输入您的秘密消息:您好抛出'std :: out_of_range'实例后调用终止what():basic_string :: at:__n(0)> = this-> size()(0)

Output: Enter your secret message: Hello terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 0) >= this->size() (which is 0)

有人可以告诉我该代码中要进行哪些更改吗?

Can anyone tell me what changes should I make in this code?

推荐答案

您的加密的字符串为空,因此使用 .at()对其进行索引会引发异常.

Your encrypted string is empty, so indexing into it with .at() throws an exception.

要解决此问题,您可以添加字符,如下所示:

To solve this problem, you could append the characters, like this:

 for(int i=0;i<original.length();i++){
        if(std::isalpha(original.at(i))){
           encrypted +=  key.at(alphabet.find(original.at(i)));
        }
        else 
           encrypted += original.at(i);
}

这是一个演示.

或者,您可以确保 encrypted 的大小与 original 的大小相同,如下所示:

Alternatively, you could ensure that encrypted has the same size as original, like this:

encrypted = original;

,然后您的循环保持不变.

and then your loop stays the same.

此外,您可以使用range-for循环来简化循环:

Also, you could simplify your loop, by using a range-for loop:

for(unsigned char c : original){
        if(std::isalpha(c)){
            encrypted +=  key.at(alphabet.find(c));
        }
        else
            encrypted += c;
    }

您可以通过结合以下两种方法来进一步简化此操作:

You could simplify this even further by combining the 2 approaches:

string encrypted = original;
for (auto &c : encrypted)
  if (std::isalpha(c))
    c = key.at(alphabet.find(c));

这是一个演示.

这篇关于替换密码加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆