【发布时间】:2016-02-19 14:09:42
【问题描述】:
我在编写涉及编写 Vigenere 密码的作业的代码的最后一部分时遇到问题。加密部分工作正常,但我无法弄清楚如何重复加密字/关键字。因此,如果需要加密的消息小于或等于关键字,则它可以正常工作,否则它会输出另外几个字符,这些字符看起来是加密的,但实际上并非如此。
这是目前为止的代码:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("YELL!\n");
return 1;
}
//check if the number of command line arguments is correct, if not, YELL!
string keyword = (argv[1]);
//get keyword
for (int j = 0, n = strlen(keyword); j < n; j++)
{
if(!isalpha(keyword[j]))
{
printf("YELL!\n");
return 1;
}
}
//check if the keyword is only alphabetical, if not, YELL!
string message = GetString();
//get plaintext
for (int j = 0, n = strlen(keyword); j < n; j++)
{
if (isupper(keyword[j]))
{
keyword[j] = (keyword[j] - 'A');
}
if (islower(keyword[j]))
{
keyword[j] = (keyword[j] - 'a');
}
}
//this is to get the numerical values from the ascii values of the keyword.
for (int i = 0, j = 0, n = strlen(message); i < n; i++, j++)
//counting through the message & the cypher
{
if (isalpha(message[i]))
{
if (isupper(message[i]))
{
message[i] = (((message[i] - 'A') + keyword[j]) % 26 + 'A');
}
if (islower(message[i]))
{
message[i] = (((message[i] - 'a') + keyword[j]) % 26 + 'a');
}
//adding a keyword value [j] to message [i] and converting back to ascii value,
//individually for upper and lowercase characters.
}
printf("%c", message[i]);
}
}
这可能是一个简单的解决方案,但我就是想不通。任何帮助将不胜感激!
【问题讨论】:
标签: c encryption cs50 vigenere