gpt4 book ai didi

c - 维吉尼亚密码困难

转载 作者:行者123 更新时间:2023-11-30 18:54:51 26 4
gpt4 key购买 nike

这是 cs50 的 Vigenere 密码。这是我第一次编码,我已经解决这个问题一周了,而且我似乎无法在第一次循环完成后打印第一个字母。

例如:

jharvard@appliance (~/Dropbox): ./viginere abcde You're key is abcdeType your text: aaaaa aaaaaa aaaaaaa aaaaaaaaabcde bcde bcdebc debcde

First a is printed but then it starts on b and in the end it doesn't print every letter. The key is chosen by the user.

I have no idea what I'm doing wrong.

for (int i = 0, j = strlen(plain_text), l = 0; i < j; i++)
{
int rotation_1 = (tolower(plain_text[i]) + (key[l] - 97)) % 122;
int rotation_2 = (plain_text[i] + (key[l] - 97)) % 122;

//if it is a letter
if (isalpha(plain_text[i]))
{
l = l % strlen(key);
//if the it is uppercase
if (isupper(plain_text[i]))
{
printf("%c", toupper(rotation_1));
}
//else if it is lowercase
else
{
printf("%c", rotation_2);
}
l++;
}
// if it is not a letter we print it as it is
else
{
printf("%c", plain_text[i]);
}
}

最佳答案

这是一个更简单的版本,其中逻辑已修复:

for (int i = 0, n = strlen(plain_text), k = 0, klen = strlen(key); i < n; i++) {
int c = (unsigned char)plain_text[i];

//if it is a letter
if (isalpha(c)) {
if (isupper(c)) {
c = 'A' + (c - 'A' + key[k] - 'a') % 26;
} else {
c = 'a' + (c - 'a' + key[k] - 'a') % 26;
}
k = (k + 1) % klen;
}
putchar(c);
}

plain_text[i]很重要如(unsigned char)因为isalphaisupper仅为 unsigned char 的所有值定义和EOFchar可能会被您的平台默认签名。

另请注意 putchar(c)printf("%c", c); 效率高得多

关于c - 维吉尼亚密码困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29460923/

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