CS50 Caesar 密码在检查命令行参数后中断
CS50 Caesar cypher disrupts after checking command-line argument
我一直在用凯撒密码编写代码(通过将输入的数字移位来编码字母)。它工作正常,直到我引入一个条件确保输入的密钥是一个数字并且以某种方式破坏了代码的工作。
我不明白这种情况与之后的代码有什么关系,有什么问题。
有人可以帮忙吗?
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
for (int j = 0; j < strlen(argv[1]); j++)
{
if (!(isdigit(argv[1][j])))
{
printf("Usage: ./caesar key\n");
return 1;
}
}
int k = atoi(argv[1]);
if (argc == 2 && k > 0)
{
string s = get_string("plaintext: ");
int m = k % 26;
//introducing an array type char of string length size
char cypher[strlen(s)];
for (int i = 0; i < strlen(s); i++)
{
//checking if it's a letter, if yes then next if
if (isalpha(s[i]))
{
//checking if it's uppercase
if (isupper(s[i]))
{
cypher[i] = (s[i] + m);
//make a round if it's beyond Z
if (cypher[i] > 'Z')
{
cypher[i] = cypher[i] - 26;
}
}
// checking if it's lowercase
else if (islower(s[i]))
{
//if it falls beyond ascii table
if ((s[i] + m) > 126)
{
cypher[i] = (s[i] - 26 + m );
}
else
{
cypher[i] = (s[i] + m);
}
//make a round if it's beyond z
if (cypher[i] > 'z')
{
cypher[i] = cypher[i] - 26;
}
}
}
// if it's not a letter - keep the initial character, write it in the cypher
else
{
cypher[i] = s[i];
}
}
printf("ciphertext: %s\n", cypher);
return 0;
}
}
C 中的 strlen 不考虑空字符
数组的长度应该是[strlen(s)+1]并且应该加上\0字符
我一直在用凯撒密码编写代码(通过将输入的数字移位来编码字母)。它工作正常,直到我引入一个条件确保输入的密钥是一个数字并且以某种方式破坏了代码的工作。
我不明白这种情况与之后的代码有什么关系,有什么问题。
有人可以帮忙吗?
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
for (int j = 0; j < strlen(argv[1]); j++)
{
if (!(isdigit(argv[1][j])))
{
printf("Usage: ./caesar key\n");
return 1;
}
}
int k = atoi(argv[1]);
if (argc == 2 && k > 0)
{
string s = get_string("plaintext: ");
int m = k % 26;
//introducing an array type char of string length size
char cypher[strlen(s)];
for (int i = 0; i < strlen(s); i++)
{
//checking if it's a letter, if yes then next if
if (isalpha(s[i]))
{
//checking if it's uppercase
if (isupper(s[i]))
{
cypher[i] = (s[i] + m);
//make a round if it's beyond Z
if (cypher[i] > 'Z')
{
cypher[i] = cypher[i] - 26;
}
}
// checking if it's lowercase
else if (islower(s[i]))
{
//if it falls beyond ascii table
if ((s[i] + m) > 126)
{
cypher[i] = (s[i] - 26 + m );
}
else
{
cypher[i] = (s[i] + m);
}
//make a round if it's beyond z
if (cypher[i] > 'z')
{
cypher[i] = cypher[i] - 26;
}
}
}
// if it's not a letter - keep the initial character, write it in the cypher
else
{
cypher[i] = s[i];
}
}
printf("ciphertext: %s\n", cypher);
return 0;
}
}
C 中的 strlen 不考虑空字符 数组的长度应该是[strlen(s)+1]并且应该加上\0字符