c-CS50凯撒密码输出错误(pset2)



我正在尝试实现一个使用凯撒密码对消息进行加密的程序。我的代码中有某种逻辑错误,我一直在努力寻找它。逻辑对我来说是有意义的,但我一直得到错误的输出。请有人指导我解决这个问题!

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
//Check that program was run with one command-line argument
if (argc == 2)
{
int n = strlen(argv[1]);
//Iterate over the provided argument to make sure all characters are digits
for (int i = 0; i < n; i++) {
if (isdigit(argv[1][i])) {
//Convert that command-line argument from a string to an int
//  int key = atoi(argv[1]);
int key = atoi(argv[1]);
//Prompt user for plaintext
string plaintext = get_string("Enter plain text: ");
printf("ciphertext: ");
//int l = strlen(plaintext);
//Iterate over each character of the plaintext:
for (int j = 0, l=strlen(plaintext); j < l; j++) {
if (isalpha(plaintext[j])) {
if (isupper(plaintext[j])) {
printf("%c", (((plaintext[i] - 65) + key) % 26) + 65);
}
if (islower(plaintext[j])) {
printf("%c", (((plaintext[i] - 97) + key) % 26) + 97);
}
}
else
{
printf("%c", plaintext[i] );
}
}
printf("n");
return 0;
}
else {
printf("Usage: ./caesar keyn");
return 1;
}
}
}
else
{
printf("Usage: ./caesar keyn");
return 1;
}
}

执行加密的代码不应位于检查argv[1]中所有字符是否为数字的循环中。首先执行验证密钥的循环。如果成功,那么询问明文并执行加密。

主要的逻辑错误是您在许多地方都有plaintext[i]。应该是plaintext[j]

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
//Check that program was run with one command-line argument
if (argc == 2)
{
int n = strlen(argv[1]);
//Iterate over the provided argument to make sure all characters are digits
for (int i = 0; i < n; i++) {
if (!isdigit(argv[1][i])) {
printf("Error: Key must be numeric");
return 1;
}
}
//Convert that command-line argument from a string to an int
int key = atoi(argv[1]);
//Prompt user for plaintext
string plaintext = get_string("Enter plain text: ");
printf("ciphertext: ");
//Iterate over each character of the plaintext:
for (int j = 0, l=strlen(plaintext); j < l; j++) {
if (isupper(plaintext[j])) {
printf("%c", (((plaintext[j] - 'A') + key) % 26) + 'A');
} else if (islower(plaintext[j])) {
printf("%c", (((plaintext[j] - 'a') + key) % 26) + 'a');
} else {
printf("%c", plaintext[j] );
}
}
printf("n");
return 0;
} else {
printf("Usage: ./caesar keyn");
return 1;
}
}

也不需要在isalpha()中嵌套isupper()islower()检查。只需使用else if测试3个互斥条件:大写字母、小写字母和其他所有条件。

并避免硬编码ASCII代码,使用字符文字。

最新更新