【问题标题】:CS50 Caesar segmentation faultCS50 凯撒分段错误
【发布时间】: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;
        }
    }


}

【问题讨论】:

    标签: c cs50


    【解决方案1】:

    我知道发生了什么!因为我需要将一些值传递给atoi(),如果我只调用./caesar,就没有我可以传递给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;
            }
        }
    
    
    }
    

    【讨论】: