c-CS50凯撒分段故障



我是新来的,正在做cs50的第二个家庭作业Caesar,除了最后一个,我的大部分复习似乎都是正确的——我无法处理缺少argv[1]的情况,这意味着如果我只打字/凯撒,它会返回分段错误。我想知道为什么当argc==1时,这个代码if (argc != 2)不能返回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 %in", 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;
}
}

}

我知道发生了什么!因为如果我只调用,我需要将一些值传递到atoi()/caesar,没有值I可以传递到atoi()中,因此导致分割错误。这意味着我需要稍微更改代码顺序,将int numberkey = atoi(key);放入else循环中。因此,代码将首先运行if (argc != 2),如果没有,则转到下一步!这是更改后的代码。

int check_the_key(int argc, string y)
{   
int number = argc;
string key = y;

if (argc != 2)
{
return 0;
}
else 
{
int numberkey = atoi(key);
if (numberkey > 0)
{
return numberkey;
}
else
{
return 0;
}
}

}

最新更新