CS50 Vigènere 问题。越界访问,未定义行为
CS50 Vigènere problem. Out of bounds access, undefined behavior
所以这是我为 CS50 Vigenère 问题提供的解决方案;我对编程还很陌生,好像才几周,所以我提前对我的代码形式表示歉意。
这里的问题是输出不是我期望的那样。
示例:
./vigenere ABC
输入:你好
输出:hfnLp
./vigenere ABC
输入:你好
输出:HFN,P
./vigenere 培根
输入:上午十一点在公园见我
输出:Neg zF av uf pCx bT gzrwEP OZ
(应该是"Negh zf av huf pcfx bt gzrwep oz")
我很无能,因为它似乎有点工作,但有些问题。
我几乎检查了我使用的每一个整数,它们都按照我的预期运行。
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main (int argc, string argv[])
{
string k = argv[1]; //key
string p; //plaintext
int j = 0; //the counter for key index
int ci; // the variable for reaching the right shifting value on both uppercase and lowercase letters
int K;//the value of the key index shift
if (argc != 2)
{
printf("input error\n");
}
else
{
p = get_string();
for (int i = 0, n = strlen(p); i < n; i++)
{
if (isupper(k[j]))
{
ci = 65;
}
else
{
ci = 97;
}
K = k[j % strlen(k)] - ci;
if (isalpha (p[i]))
{
printf("%c", p[i] + K);
j++;
}
else
{
printf("%c", p[i]);
}
}
printf("\n");
}
}
在 strlen(k)
次迭代后,isupper(k[j])
使用了超出 k
末尾的索引。
您可以更改:
if (isupper(k[j]))
{
ci = 65;
}
else
{
ci = 97;
}
K = k[j % strlen(k)] - ci;
至:
K = toupper(k[j % strlen(k)]) - 'A';
(注意这依赖于 C 标准不保证的 属性,即字母的字符代码是连续的并按字母顺序排列。)
所以这是我为 CS50 Vigenère 问题提供的解决方案;我对编程还很陌生,好像才几周,所以我提前对我的代码形式表示歉意。
这里的问题是输出不是我期望的那样。
示例:
./vigenere ABC
输入:你好
输出:hfnLp
./vigenere ABC
输入:你好
输出:HFN,P
./vigenere 培根
输入:上午十一点在公园见我
输出:Neg zF av uf pCx bT gzrwEP OZ
(应该是"Negh zf av huf pcfx bt gzrwep oz")
我很无能,因为它似乎有点工作,但有些问题。
我几乎检查了我使用的每一个整数,它们都按照我的预期运行。
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main (int argc, string argv[])
{
string k = argv[1]; //key
string p; //plaintext
int j = 0; //the counter for key index
int ci; // the variable for reaching the right shifting value on both uppercase and lowercase letters
int K;//the value of the key index shift
if (argc != 2)
{
printf("input error\n");
}
else
{
p = get_string();
for (int i = 0, n = strlen(p); i < n; i++)
{
if (isupper(k[j]))
{
ci = 65;
}
else
{
ci = 97;
}
K = k[j % strlen(k)] - ci;
if (isalpha (p[i]))
{
printf("%c", p[i] + K);
j++;
}
else
{
printf("%c", p[i]);
}
}
printf("\n");
}
}
在 strlen(k)
次迭代后,isupper(k[j])
使用了超出 k
末尾的索引。
您可以更改:
if (isupper(k[j]))
{
ci = 65;
}
else
{
ci = 97;
}
K = k[j % strlen(k)] - ci;
至:
K = toupper(k[j % strlen(k)]) - 'A';
(注意这依赖于 C 标准不保证的 属性,即字母的字符代码是连续的并按字母顺序排列。)