读书人

怎么控制C++中数组的长度

发布时间: 2012-02-09 18:22:27 作者: rapoo

求助如何控制C++中数组的长度
#include <iostream.h>

char* jiami(const char* str);
char* jiemi(const char* str);
const char key[]={4,9,6,2,8,7,3};
const keylen=sizeof(key);

void main()
{
char* s= "the result of 3 and 2 is not 8 ";
cout < < "\n原文为: \n " < <s < <endl;

char* result1=jiami(s);

cout < < "\n密文为: \n " < <result1 < <endl;

char* result2=jiemi(result1);

cout < < "\n解密之后为: \n " < <result2 < <endl;

delete[] result1;
delete[] result2;
}

char* jiami(const char* str)
{
int len=strlen(str);
char* result = new char[len+1];
for(int i=0,j=0; i <len; i++,j=(j+1)%keylen){
result[i] = str[i]+key[j];
if(result[i]> 122)
result[i]-=90;
}
return result;
}

char* jiemi(const char* str)
{
int len=strlen(str);
char* result = new char[len+1];
for(int i=0,j=0; i <len; i++,j=(j+1)%keylen){
result[i] = str[i]-key[j];
if(result[i] <32)
result[i]+=90;
}
return result;
}结果如下:
-------------------------------------

原文为:
the result of 3 and 2 is not 8

密文为:
xqk "zlvyuz "wm#7)gpl '5$ry "vvw$A妄?

解密之后为:
the result of 3 and 2 is not 8!UOPT妄
Press any key to continue

-------------------------------------
后面出现了乱码,而且发现result1的长度等于35,
result2的长度等于41,不知道为什么??我觉得问题出在
调用函数上.

理想的输出应该是:
-------------------------------------

原文为:
the result of 3 and 2 is not 8

密文为:
xqk "zlvyuz "wm#7)gpl '5$ry "vvw$A

解密之后为:
the result of 3 and 2 is not 8
Press any key to continue-------------------------------------

[解决办法]
少了两个
result[len] = '\0 ';

读书人网 >C++

热点推荐