簡體   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