c - 为什么我在 C 语言中收到警告 'Segmentation fault, core dumped'

标签 c cs50 vigenere

我正在编写一个将纯文本加密为密文的程序。当我运行程序时,我收到了段错误、核心转储错误。

这是我的代码:

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

int main(int argc, string argv[])
{
    int k = 0;

    // continues the program if 2 and no more than 2 command line arguments exist and argv[1] contains alphabetical characters only
    if(argc == 2 && argc == isalpha(argv[1]))
    {
        k = atoi(argv[1]);
    }

    // re-prompts user to enter only 2 command line arguments and the second should consist of only alphabetical characters
    else
    {
        printf("You must enter a command line argument using only alphabetical characters!\n");
        return 1;
    }

    string text = GetString();
    int cipher;
    int key;

    // loops through each charcter in key and gives each character a valule to add to plain text
    for (int j = 0, n = strlen(argv[1]); j < n; j++)
    {
        if (isalpha(argv[1][j]))
        {
            if (isupper(argv[1][j]))
            {
                key = 26 - (91 - argv[1][j]);
            }

            else
            {
                key = 26 - (123 - argv[1][j]);
            }
        }

        else
        {
            key = argv[1][j];
        }

        // loops through plaintext entered by user and changes text to ciphertext according to key
        for (int i = 0, l = strlen(text); i < l; i++)
        {
            if (isalpha(text[i]))
            {
                cipher = (text[i] + key) % n;
                printf("%c", cipher);
            }

            else
            {
                printf("%c", text[i]);
            }
        }
    }
    printf("\n");

}

最佳答案

目前也在完成这个确切的教程并遇到了相同的错误。我认为问题在于您在字符串上使用 isalpha(argv[1]) 而我认为 isalpha 仅适用于单个字符。我最终使用了一个 for 循环,使用 argv[1][i] 逐个字符地运行 argv[1] 关键字。

对此非常陌生,所以我希望我没有将您引向错误的方向。

关于c - 为什么我在 C 语言中收到警告 'Segmentation fault, core dumped',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21707026/

相关文章:

c - 在 Cygwin 下链接 Windows .dll+.lib 文件组合和 GCC?

c - Valgrind 提示内存泄漏

cs50 pset5 为什么我的图像恢复程序只能恢复 50 个图像中的 49 个?

c - The C Programming Language 示例 1.9 的难点

c - 如何更改 Rich Edit 控件中的下划线颜色 (Win32/C)

c - 为什么我在 C 中遇到段错误?

c - 每当我在此代码中输入 4.2 时,nm 的值为 19,其中预期为 20

python - 使用Python分析文本字符串中的二元组

c - Vigenère 密码,C 语言问题

CS50 Pset2。维杰内尔。上文本到下键,反之亦然问题