gpt4 book ai didi

C 凯撒密码 ASCII 字母换行

转载 作者:太空宇宙 更新时间:2023-11-04 08:44:30 24 4
gpt4 key购买 nike

我是 C 的新手。我希望能够将字母表中的字母“x”移动多次以创建基本密码。

我在使用 islower() 函数时遇到问题。我正在使用“i”,但无法将其更改为字符。

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

string p;

int main(int argc, string argv[])
{
//if argument count does not equal 2, exit and return 1
if (argc != 2)
{
printf("Less or more than 2 arguments given, exiting...\n");
return 1;
}
else //prompt user for plaintext to encrypt
{
p = GetString();
}

//take the second part of the array (the int entered by user) and store as k (used as the encryption key)
//string k = argv[1];
int k = atoi(argv[1]);

//function:
// c = (p + k) % 26;
//iterate over the characters in the string
//p represents the position in the alphabet of a plaintext letter
//c likewise represents a position in the alphabet
char new;
for (int i = 0, n = strlen(p); i < n; i++)
if (islower((char)i))
{
//printf("%c\n", p[i] + (k % 26));
printf("This prints p:%s\n", p);
printf("This prints i:%d\n", (char)i);
printf("This prints k:%d\n", k);
printf("This prints output of lower(i):%d\n", islower(i));
new = (p[i] - 97);
new += k;
//printf("%d\n", new %26 + 97);
//printf("i = |%c| is lowercase\n", i);
printf("%c\n", new % 26 + 97);
}
else {
//printf("%c", p[i] + (k % 26));
printf("This prints p:%s\n", p);
printf("This prints i:%d\n", (char)i);
printf("This prints k:%d\n", k);
printf("This prints output of lower(i):%d\n", islower(i));
new = (p[i] - 65);
new += k;
//printf("%d\n", new % 26 + 65);
//printf("i = |%c| is uppercase\n", i);
printf("%c\n", new % 26 + 65);
}
printf("\n");
}

输出:

jharvard@appliance (~/Dropbox/CS50x/pset2): ./caesar2 1
zZ < here is my input
This prints p:zZ
This prints i:0
This prints k:1
This prints output of lower(i):0
G < here is fails, lower case z should move to lower case a
This prints p:zZ
This prints i:1
This prints k:1
This prints output of lower(i):0
A < here is a success! upper case Z moves to upper case A

最佳答案

C 中使用的英文字母表是按 ASCII 定义的。 “Z”(ASCII 90)后仅跟有“{”(ASCII 91)。要返回“A”,您应该按以下方式进行所有转换:

  1. 将你的 ASCII 字符减去 65。它会导致输出介于 0 之间到 25(含)。
  2. 添加位移(移动距离)。
  3. 对 26 取模,以环绕你的结果。
  4. 再次加回 65。

请记住,这仅适用于英语的大写字母。因此,您可能希望使用 ctype.h 库中的 toupper()

如果您想为小字符添加类似的功能,请执行上述步骤,将 65 替换为 97。要检查您得到的是小字符还是大写字符,请使用 isupper()。您必须为特殊字符添加更多特定代码。

关于C 凯撒密码 ASCII 字母换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22208139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com