【发布时间】:2020-08-20 05:00:07
【问题描述】:
我创建了这个程序,但我在 CS50 上遇到错误,表明我没有正确执行任何操作。
要求如下:
在名为 caesar 的目录中的名为 caesar.c 的文件中实现您的程序。
您的程序必须接受一个命令行参数,一个非负整数。为了便于讨论,我们称它为 k。
如果您的程序在没有任何命令行参数或多个命令行参数的情况下执行,您的程序应该打印您选择的错误消息(使用 printf)并从 main 返回值 1(这往往立即表示错误)。
如果命令行参数的任何字符不是十进制数字,您的程序应该打印消息 Usage: ./caesar key 并从 main 返回值 1。
不要假设 k 会小于或等于 26。您的程序应该适用于 k 小于 2^31 - 26 的所有非负整数值。换句话说,您不必担心如果如果用户选择的 k 值太大或几乎太大而无法放入 int,您的程序最终会中断。 (回想一下 int 可能会溢出。)但是,即使 k 大于 26,程序输入中的字母字符也应该在程序输出中保持字母字符。例如,如果 k 为 27,则
根据http://www.asciichart.com/[asciichart.com],即使 [ 在 ASCII 中距离 A 27 个位置,A 也不应该变为 [; A 应该变成 B,因为 B 离 A 有 27 个位置,前提是你从 Z 绕到 A。
您的程序必须输出明文:(不带换行符),然后提示用户输入明文字符串(使用 get_string)。
您的程序必须输出密文:(不带换行符)后跟明文对应的密文,明文中的每个字母字符“旋转”k 个位置;非字母字符应原样输出。
你的程序必须保持大小写:大写字母,虽然轮换,但必须保持大写字母;小写字母虽然旋转,但必须保持小写字母。
输出密文后,应打印换行符。然后你的程序应该通过从 main 返回 0 来退出。
我的代码:
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
//check if k inputed
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
//value k is the number after ./caesar
int k = atoi(argv[1]) % 26;
int x = 0;
int s = strlen(argv[1]);
//check if k is a positive integer
if (k < 0)
{
printf("Usage: .caesar key\n");
return 1;
}
else
{
//check for arguments
for (int i = 0; i < s; i++)
{
if (isalpha (argv[1][i]))
{
continue;
}
else if (isalnum (argv[1][i]))
{
x++;
}
else
{
continue;
}
}
if (x != s)
{
printf("Usage: ./caesar key\n");
}
else if (x == s)
{
//get plaintext
string plain_text = get_string("plaintext: ");
printf("ciphertext: ");
for (int y = 0; y <= strlen(plain_text); y++)
{
//change letters
if (isalpha(plain_text[y]))
{
char p = plain_text[y];
int cipher_int = p + k;
if (isupper(p))
{
while(cipher_int >= 90)
{
cipher_int -= 26;
}
char cipher_text = cipher_int;
printf("%c", cipher_text);
}
if (islower(p))
{
while(cipher_int >= 122)
{
cipher_int -= 26;
}
char cipher_text = cipher_int;
printf("%c", cipher_text);
}
}
else
{
printf("%c", plain_text[y]);
}
}
printf("\n");
}
}
return 0;
}
【问题讨论】:
-
CS50 是否指定你在 StackOverflow 中询问如何解决你的作业?
-
您执行的第二个测试(对于参数中的所有字符都是数字)不打印请求的消息,它打印
.caesar而不是./caesar。 -
@RadekDulny:您可以通过点击分数下方的灰色复选标记来接受其中一个答案
标签: c encryption cs50 caesar-cipher