【发布时间】:2020-03-21 14:03:34
【问题描述】:
我是新来的,正在做cs50的第二个作业Caesar,除了最后一个之外,我的大部分评论似乎都是正确的——我无法处理缺少argv[1]的情况,这意味着如果我只输入. /caesar,它将返回分段错误。我想知道为什么这个代码if (argc != 2) 在 argc == 1 时不能返回 0,但是当 argc > 1 时它可以工作,我觉得这很奇怪。谁能帮我??提前致谢!
# include <stdio.h>
# include <cs50.h>
# include <string.h>
# include <ctype.h>
# include <math.h>
# include <stdlib.h>
int check_the_key(int argc, string y);
int main(int argc, string argv[])
{
string x = argv[1];
int y = argc;
int k = check_the_key(y, x);
if (k == 0)
{
printf("ERROR!!!!!\n");
return 1;
}
else
{
// printf("The key is %i\n", k);
string text = get_string("Input your text:");
int i;
int n;
printf("ciphertext: ");
for (i = 0, n = strlen(text); i < n; i++)
{
if (islower(text[i]))
{
printf("%c", (text[i] - 97 + k) % 26 + 97 );
}
else if (isupper(text[i]))
{
printf("%c", (text[i] - 65 + k) % 26 + 65);
}
else
{
printf("%c", text[i]);
}
}
printf("\n");
return 0;
}
}
int check_the_key(int argc, string y)
{
int number = argc;
string key = y;
int numberkey = atoi(key);
if (argc != 2)
{
return 0;
}
else
{
if (numberkey > 0)
{
return numberkey;
}
else
{
return 0;
}
}
}
【问题讨论】: