【发布时间】:2022-01-25 08:15:36
【问题描述】:
我正在为 CS50 的 Pset2 创建一个替换程序,在该程序中我输入一个 26 个字母的密钥,然后输入一些文本,它会根据密钥上的相应字母对其进行加密,当输入具有重复字母的密钥时,它会发送错误消息并返回1 正如预期的那样,但它似乎只是停止了程序。我该如何解决这个问题?
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
string key = argv[argc - 1];
for (int s = 0; s < strlen(key); s++)
{
if (key[0] == tolower(key[s]) || key[0] == toupper(key[s]) )
{
printf("Key must consist of 26 alphabetic characters.");
return 1;
}
}
if (strlen(key) != 26)
{
printf("Usage: ./substitution key\n");
printf("Key must consist of 26 alphabetic characters.\n");
return 1;
}
int keylen = strlen(key);
string plaintext = get_string("Enter the plaintext: ");
char ciphertext [strlen(plaintext)];
int move[strlen(plaintext)];
printf("ciphertext: ");
if (keylen == 26)
{
for (int counter = 0; counter < strlen(plaintext); counter++)
{
if (plaintext[counter] >= 'a' && plaintext[counter] <= 'z')
{
move[counter] = (plaintext[counter]) - 97;
ciphertext[counter] = key[move[counter]];
}
else if (plaintext[counter] >= 'A' && plaintext[counter] <= 'Z')
{
move[counter] = plaintext[counter] - 65;
ciphertext[counter] =key[move[counter]];
}
else if (plaintext[counter] < 'A')
{
ciphertext[counter] = plaintext[counter];
}
else if (plaintext[counter] > 'z')
{
ciphertext[counter] = plaintext[counter];
}
else if (plaintext[counter] > 'Z' && plaintext[counter] < 'a')
{
ciphertext[counter] = plaintext[counter];
}
}
for (int loop = 0; loop < strlen(plaintext); loop++)
{
if (plaintext[loop] >= 'a' && plaintext[loop] <= 'z')
{
printf("%c", tolower(ciphertext[loop]));
}
else if (plaintext[loop] >= 'A' && plaintext[loop] <= 'Z')
{
printf("%c", toupper(ciphertext[loop]));
}
else
{
printf("%c", ciphertext[loop]);
}
}
printf("\n");
return 0;
}
for (int i = 0; i < 27; i++)
{
if (key[i] < 'A' || key[i] > 'Z')
{
if (key[i] < 'a' || key[i] > 'z')
{
printf("Key must only contain alphabetic characters.");
return 1;
}
}
}
}
【问题讨论】:
-
到底有什么问题?
-
从 main 调用的 return 通常确实会结束执行。如果您希望返回更复杂的流程,请考虑制作更多功能。还要考虑循环中的继续和中断。
标签: c error-handling cs50