繁体   English   中英

CS50 凯撒 output 作为 aaaaa

[英]CS50 Caesar output comes as aaaaa

出于某种原因,当我更改字符串 s 的副本(字符串 c)时,字符串 s 也被更改并且 for 循环 j 继续循环直到它到达字符串字母表中的 position 零,即'a'。

int key = atoi(keys);

    string s = get_string("plaintext: ");
    string c = s;

    int length = strlen(s);

    string alphabet = "abcdefghijklmnopqrstuvwxyz";
    string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    int position = 0;

    for (int i = 0; i < length; i++)
    {
        printf("Before Conversion: %c\n",s[i]);

        for (int j = 0; j < 26; j++)
        {

            if(s[i] == alphabet[j])
            {
                position = (j + key) % 26;
                c[i] = alphabet[position];
                printf("Ascii: %i + Key: %i.. Position = %i\n",j,key,position);

                position = 0;
                printf("Not Converted: %c\n",s[i]);
                printf("After conversion: %c\n\n",c[i]);
            }
            if(s[i] == ALPHABET[j])
            {
                position = (j + key) % 26;
                c[i] = ALPHABET[position];
                printf("Ascii: %i + Key: %i.. Position = %i\n",j,key,position);

                position = 0;
                printf("After conversion: %c\n\n",c[i]);
            }
        }
    }

    printf("ciphertext: %s\n",c);

改变:

string s = get_string("plaintext: ");
string c = s;

string s = get_string("plaintext: ");

string c = malloc(strlen(s) + 1);
strcpy(c, s);

这将使它工作。 这里最大的问题是CS50正在使用的课程

typedef char* string;

为新生隐藏指针的复杂性,但实际上它只会造成混乱。 为了完全理解上述解决方案为何有效,您需要了解指针和动态分配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM