【发布时间】:2022-09-30 21:20:55
【问题描述】:
我为 cs50 编写了一个程序,它应该接收(整数)key(在运行时)并输出plaintext 的提示,然后根据凯撒密码函数输出明文的加密版本。
当我在 cs50 IDE 中运行该程序时,它会在终端 (make caesar) 中编译,当我在运行时输入 \'key\' 时(例如./caesar 2),我会收到提示 [Plaintext: ] 和例如我输入Hello。输出将是[Ciphertext: 99102109109112],而不是预期的[Ciphertext: JGOOQ]。
这是我的代码:
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// Get the \'key\' value at run-time (./ceasar \'key\').
// key_value must be a digit/number).
// String argv[1] must be converted to int.
// Prompt user for plaintext.
// plaintext must be converted by casaer cipher to ciphertext.
// Print ciphertext.
// Declaring variables.
string plaintext;
string ciphertext;
int key_value;
// declaring the caesar cipher function (takes in an array of characters (aka string) and an int).
void caesar_cipher(char str[], int shift_value);
int main(int argc, string argv[])
{
// check if there are two arguments at run-time and the second argument (argv[1]) is a digit.
if (argc == 2 && isdigit(*argv[1]))
{
// convert string argv[s] to an int.
key_value = atoi(argv[1]);
// Prompt user for plaintext.
plaintext = get_string(\"Plaintext: \");
printf(\"Ciphertext: \");
caesar_cipher(plaintext, key_value);
// new line
printf(\"\\n\");
return 0;
}
else
{
printf(\"Usage: ./caesar \'key\'\\n\");
return 1;
}
}
// char str[] will take in \'plaintext\' and int shift_value will take in \'key\'
void caesar_cipher(char str[], int shift_value)
{
int s = 0;
char c = str[s];
if (c != \'\\0\')
{
// iterate through every character, letter-by-letter.
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
// case for uppercase letters.
if (isupper(c))
{
printf(\"%i\", (((plaintext[i] - \'A\') + shift_value) %
26) + \'Z\');
}
// case for lowercase letters.
else if (islower(c))
{
printf(\"%i\", (((plaintext[i] - \'a\') + shift_value) % 26)
+ \'z\');
}
else
{
printf(\"%c\", c);
}
}
}
}
-
你为什么要循环调用
caesar_cipher? -
else if (str[i] >= \'a\' && str[i] <= \'a\')--->else if (str[i] >= \'a\' && str[i] <= \'z\')z!不是 -
@CGi03
islower()更好...
标签: c pointers debugging cs50 caesar-cipher