简体   繁体   中英

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'.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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