【发布时间】:2020-06-25 08:35:07
【问题描述】:
我卡在 Pset2 中凯撒的最后一部分。我应该做的是根据用户一开始给出的密钥对用户的输入(明文)进行加密。这是我必须使用的公式:
密文第i个字符=(明文第i个字符+密钥)%26
我已经坚持了将近 2 周,但我仍然不知道如何实施该公式(尽管它是如何工作的)。这是我到目前为止所做的,但显然它有我不知道如何修复的错误。
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[]) //command line argument
{
if (argc != 2) //correct argument count
{
printf ("usage: ./caesar key\n");
return 1;
}
for (int i = 0 ; argv[1][i] ; i++)
{
if (isdigit(argv[1][i])) //if digit = correct
{
printf("success\n");
}
else if(isalpha(argv[1][i])) // if letter= wrong
{
printf ("usage: ./caesar key\n");
return 1;
}
}
string plaintext = get_string("plaintext;");
for( int m = 0 ; m<strlen(plaintext) ; m++)
{
string ciphertext[m];
if(isupper(plaintext[m]))
{
ciphertext[m] = (plaintext[m] + argv[1]) % 26;
}
else if(islower(plaintext[m]))
{
ciphertext[m] = (plaintext[m] + argv[1]) % 26;
}
printf("%s\n", ciphertext[m]);
}
}
【问题讨论】:
-
公式不应该是
ciphertext's i'th character = (plaintext's i'th character + i'th char of key) % 26 -
我希望
ciphertext's i'th character = (plaintext's i'th character + key) % 26而不是ciphertext's i'th character = (plaintext's i'th character - 'a' + key) % 26 +'a'。
标签: c cs50 caesar-cipher