caesar密码算法c++

caesar cipher algorithm c++

本文关键字:c++ 算法 密码 caesar      更新时间:2023-10-16

我正在尝试用c++语言实现Ceaser密码

#include <iostream>
#include <string>
#include <locale>
using namespace std;
int main()
{
    string word;

    getline(cin,word);
    for(int i=0; i<word.length();i++)
    {
        if(isalnum(word[i]))
        {
//shift by 3
            word[i]+= 3;
        }
    }
    cout << word ;
    return 0;
}

我想要的是限制输出也只针对字母和数字。例如,如果我想将z移位3,那么输出将是"c",而不是我的代码中的"}"。

编译器比人类更善于处理繁琐的细节,所以在这种情况下,我会编写代码来清楚地显示您的意图,然后让编译器计算出数字。

例如,如果你想移动一个字母,你不是真的只想在a到Z范围内的字母索引上加3,然后乘以26——从a到Z的字母数吗?这正是你想要的——围绕字母的圆圈从A到Z旋转,其中有26个,不用担心ASCII值。

在这种情况下,您可以让编译器为您计算:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
    int shift = 3;
    char* input = "Is it 90 with a ZERO?";
    printf("%sn", input);
    int length = strlen(input);
    char* output = malloc(length + 1);
    output[length] = '';
    for (int i = 0; i < length; i++)
    {
        char c = input[i];
        if (c >= 'A' && c <= 'Z')
        {
            c = (((c - 'A') + shift) % 26) + 'A';
        }
        else if (c >= 'a' && c <= 'z')
        {
            c = (((c - 'a') + shift) % 26) + 'a';
        }
        else if (c >= '0' && c <= '9')
        {
            c = (((c - '0') + shift) % 10) + '0';
        }
        output[i] = c;
    }
    printf("%sn", output);
}

如果你不担心速度或内存占用,你为什么要承担这个责任?

您必须确保它不会超出ASCII字母的有效范围。这样做的一种方法是将输入转换为小写,然后确保添加shift时不超过122z在ASCII中的值)。

if (word[i] + SHIFT > 'z') {
    SHIFT -= 123 - word[i];
    word[i] = 'a';    // go back to the beginning
    word[i] += SHIFT; // add on the remaining amount
}

这应该可以工作。这是假设只有小写字母。

        word[i]+= 3;
        //at this point word[i] might have cross the ascii limit for lower case letters

即可以是CCD_ 3。小写字母的Ascii范围为97-122所以我们用mod来包装它。但现在可能是word[i]<97,它再次超出范围,所以我们将97添加到它中

        word[i]%=123;
        if(word[i]<97)word[i]+=97;

示例z

     word[i]+=3 makes word[i] as 125  //out of range
     word[i]%=123      //word[i]=3
     word[i]+=97          //word[i]=99=c