首页 > 解决方案 > CS50 Caesar 上的分段错误和调试

问题描述

嘿,我之前问了一个与此代码相关的问题,并得到了很多有用的答案(我很擅长编码)。虽然我克服了最初的问题并更正了一些错误,但我遇到了另一个我似乎无法修复的错误。我不断收到分段错误,但我希望它提示用户提供第二个参数。除此之外,当我给出数字时,代码似乎并没有真正加密文本我错过了任何建议或大声问题吗?

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, string argv[])
{

int num;
int k = atoi(argv[1]);
string output;

        if(argc != 2)
        {
                printf("K not included in command");
                return 1;
        }



        string s = get_string("Insert Lowercase Message:");

        for (int i = 0, n = strlen(s); i < n; i++)
        {
                char c = s[i];
                if (c >= 'A' && c <= 'Z')
                {
                        num = 'A';
                if (c >= 'a' && c <= 'z')
                        num = 'a';
                
                printf("%c", (c - num + k) % 26 + num);
                }
                else
                        printf("%c", c);
        }
        
        

}

标签: csegmentation-faultcs50

解决方案


在测试字母大小写的地方,您的大括号未对齐。它的编写方式,如果遇到小写字母,大写测试将失败,您将通过else案例。你想要的是这样的:

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, string argv[])
{

    int num;
    int k;
    string output;
    char c;

    if(argc != 2)
    {
        printf("K not included in command");
        return 1;
    }

    k = atoi(argv[1]);
    string s = get_string("Insert Lowercase Message:");

    for (int i = 0; c = s[i]; i++)
    {
        if (isalpha(c))
        {
            if (isupper(c))
                num = 'A';
            else   // islower
                num = 'a';
            printf("%c", (c - num + k) % 26 + num);
        }
        else
            printf("%c", c);
    }
}

推荐阅读