C语言 尝试编写循环以将字符串中的字母替换为同一索引处不同字符串中的字母,但循环提前结束

h43kikqp  于 2022-12-03  发布在  其他
关注(0)|答案(1)|浏览(81)

我正在编写一个程序,该程序应该将一个密钥作为输入参数,并使用该密钥对用户输入的单词进行加密。
该计划应:
1.要求使用者输入要加密的纯文字
1.规范字母大小写
1.从明文中取出每个字母,并找到该字母的索引(A = 0,B = 1,...)
1.查看键字符串(输入参数)中在此位置索引的字母
1.把这封加密的信分配给一个新的名为cypher的诱饵
1.打印新的密文字符串。
我使用的代码是:

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

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

    //Check that key has 26 letters or end program
    string key = argv[1];
    if (strlen(argv[1]) != 26)
    {
        printf("Key must contain 26 characters\n");
        return 1;
    }

    //Get plaintext
    string plain = get_string("plaintext: ");

    //Make key all letters upper case
    for (int i = 0; i < plain[i]; i++)
    {
        if (islower(plain[i]))
        {
            plain[i] = plain[i] - 32;
        }
        printf("%c", plain[i]);
    }
    printf("\n");

//Encrypt
    int index[] = {};
    int cypher[] = {};

    //Cycle through the letters in the word to be encoded
    //printf("cyphertext: ");
    printf("%c\n", key[79 - 65]);
    for (int i = 0; i < strlen(plain); i++)
    {
        printf("index in key: %i\n", plain[i] - 65);
        cypher[i] = key[plain[i] - 65];
        printf("cypher: %c\n", cypher[i]);
    }
    printf("\n");
}

在for循环的第四个循环将新值赋给密码字符串之前,一切都执行得很好。
我希望最后一个for循环对输入的每个字母循环一次(例如input:你好;循环:5),但我发现它停在4,只输出:“见鬼”。
我试探着:

  • 包含4个字符的单词-执行正确数量的循环,但在最后一个循环后仍然得到Segmentation fault (core dumped)
  • 3个字符的单词-执行正常,无错误
  • 包含5个以上字母的单词-出错前仍循环4次

救命啊!

v8wbuo2f

v8wbuo2f1#

for循环应该从0迭代到plain的长度。
//获取明文

string plain = get_string("plaintext: ");

    //Make key all letters upper case
    for (int i = 0; i < strlen(plain); i++)
    {
        if (islower(plain[i]))
        {
            plain[i] = plain[i] - 32;
        }
        printf("%c", plain[i]);
    }

//*** Must allocate memory for array
//Encrypt
    int index[100] = {};
    int cypher[100] = {};

    //Cycle through the letters in the word to be encoded
    //printf("cyphertext: ");
    printf("%c\n", key[79 - 65]);
    for (int i = 0; i < strlen(plain); i++)
    {
        printf("index in key: %i\n", plain[i] - 65);
        cypher[i] = key[plain[i] - 65];
        printf("cypher: %c\n", cypher[i]);
    }
    printf("\n");

相关问题