我正在尝试实现一个使用Caesar密码对消息进行加密的程序。我的代码中存在某种逻辑错误,并且我一直在努力寻找它。逻辑对我来说很有意义,但是我一直得到错误的输出。请有人可以指导我解决这个问题!
#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 key\n");
return 1;
}
}
}
else
{
printf("Usage: ./caesar key\n");
return 1;
}
}
答案 0 :(得分:2)
执行加密的代码不应位于检查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 key\n");
return 1;
}
}
也不需要将isupper()
和islower()
检查嵌套在isalpha()
内。只需使用else if
测试3个互斥条件:大写字母,小写字母和其他所有内容。
并避免硬编码ASCII码,请使用字符文字。