我正在做一个作业,我必须通过在要编码/解码的字符串上添加/减去“密码”(另一个字符串)来“编码”和“解码”字符串。但是,当我运行它时,我得到的结果与正确的输出类似,但仍然不正确。我认为这可能与我添加/减去两个字符串的方式有关。抱歉,这很琐碎,但我是初学者。我将不胜感激!
这是用于编码和解码的代码(注意:我还必须编写一个函数来查找字符串的长度,因为不允许包含头文件)
int mystrlen(const unsigned char *string)
{
int length = 0; /* holds the value of the length of the string */
/* goes through elements of string not counting the null character */
while(*string != '\0')
{
string++; /* moves to the next letter of the string */
length ++; /* counts how many letters there are */
}
return length; /* returns the length of the string */
}
void jumble(unsigned char *string, const unsigned char *password,
enum CODE_METHOD method, int passes)
{
if(method == ENCODE)
{
int i;
for(i = 1; i <= passes; i++)
{
while(*string != '\0')
{
*string = *string + *password;
string++;
password++;
}
}
}
else
{
int i;
for(i = 1; i <= passes; i++)
{
while(*string != '\0')
{
*string = (*string) - (*password);
string++;
password++;
}
}
}
}
这是正确的输出:
Test0 ======================================
length of a is 1
length of b is 4
length of c is 0
length of d is 174
Test1 ======================================
Original phrase:
THIS IS A SECRET.
Encoded phrase:
xkstDl}AeC}fguouR
Test2 ======================================
Encoded phrase:
xkstDl}AeC}fguouR
Decoded back:
THIS IS A SECRET.
这就是我得到的:
Test0 ======================================
length of a is 1
length of b is 4
length of c is 0
length of d is 174
Test1 ======================================
Original phrase:
THIS IS A SECRET.
Encoded phrase:
xkst ┴╛ô╡@╓àh1
Test2 ======================================
Encoded phrase:
xkstDl}AeC}fguouR
Decoded back:
THISD5° e1ocp!
再次感谢您!
答案 0 :(得分:1)
由于您的文本字符串比密码字符串长 ,因此您的密码字符串末尾超出了限制(例如,文本为8个字符,但您只有4个密码字符)。这是未定义的行为(例如,此后为随机字符)
以下是一些代码,当密码到达末尾时,这些代码会返回密码的开头。我只是猜测这就是算法所需要的。您可能需要对其进行调整,以匹配所需的确切算法/结果。
此外,每次通过都必须将string
变量重置为开头。否则,只有 first 通过才会生效。
void
jumble(unsigned char *string, const unsigned char *password, enum CODE_METHOD method, int passes)
{
int pwlen;
unsigned char *str;
unsigned char *pw;
pw = password;
if (method == ENCODE) {
int i;
for (i = 1; i <= passes; i++) {
//pw = password; ?
str = string;
while (*str != '\0') {
*str = *str + *pw;
str++;
if (*++pw == 0)
pw = password;
}
}
}
else {
int i;
for (i = 1; i <= passes; i++) {
//pw = password; ?
str = string;
while (*str != '\0') {
*str = (*str) - *pw;
str++;
if (*++pw == 0)
pw = password;
}
}
}
}