caesar密码算法c++
caesar cipher algorithm c++
我正在尝试用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时不超过122
(z
在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
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 算法问题:查找从堆栈中弹出的所有序列
- 下面是排序算法O(n)吗
- KMP算法和LPS表构造的运行时间
- 为什么我的排序算法会更改数组值
- 求最大元素位置的分治算法
- 具有非整数边容量的最大流量的Dinic算法
- 到连接组件算法的问题(递归)
- STL算法函数在多个一维容器上的使用
- 读取最后一行代码算法 - c++ 时出现问题
- 括号更改 O(n) 算法
- std::unordered_map 搜索算法是如何实现的?
- 如何实现高效的算法来计算大型数据集的多个不同值?
- 如何在 Mac 上使用 c++17 并行标准库算法?