CS50 凯撒输出作为 aaaaa
CS50 Caesar output comes as aaaaa
出于某种原因,当我更改字符串 s 的副本(字符串 c)时,字符串 s 也会更改并且 for 循环 j 继续循环直到它到达字符串字母表中的位置零,即 '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;
为新生隐藏指针的复杂性,但实际上它只是造成混乱。为了完全理解上述解决方案为何有效,您需要了解指针和动态分配。
出于某种原因,当我更改字符串 s 的副本(字符串 c)时,字符串 s 也会更改并且 for 循环 j 继续循环直到它到达字符串字母表中的位置零,即 '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;
为新生隐藏指针的复杂性,但实际上它只是造成混乱。为了完全理解上述解决方案为何有效,您需要了解指针和动态分配。