简体   繁体   English

CS50 凯撒 output 作为 aaaaa

[英]CS50 Caesar output comes as aaaaa

For some reason when I change the copy of string s that is (string c), string s also gets changed and for loop j keeps on looping until it reached position zero in string alphabet which is 'a'.出于某种原因,当我更改字符串 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);

Change:改变:

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

to

string s = get_string("plaintext: ");

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

That will make it work.这将使它工作。 The biggest problem here is that the course CS50 is using这里最大的问题是CS50正在使用的课程

typedef char* string;

to hide the complexity of pointers for new students, but in reality it just causes confusion.为新生隐藏指针的复杂性,但实际上它只会造成混乱。 In order to fully understand why the above solution works, you need to understand pointers and dynamic allocation.为了完全理解上述解决方案为何有效,您需要了解指针和动态分配。

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

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