我想用C ++以简单的方式加密消息,所以我写了这个函数:
char* encrypt(char* not_encrypted){
char* encrypted = new char[strlen(not_encrypted)];
char* begin = encrypted;
while (*not_encrypted != '\0') {
*encrypted = *not_encrypted + 3;
not_encrypted++;
encrypted++;
}
encrypted = '\0';
return begin;
}
但它没有像我预期的那样奏效。 以下是它的工作示例:
输入字符串:asf
DVI
^ PC
我想知道我犯了什么错误。
答案 0 :(得分:2)
使用您在问题中使用的样式,可能会得到您想要的样式:
#include <string.h>
#include <stdio.h>
#include <iostream>
char* encrypt(const char* not_encrypted)
{
char* encrypted = new char[strlen(not_encrypted) + 1];
char* begin = encrypted;
while (*not_encrypted != '\0')
{
*encrypted++ = *not_encrypted++ + 3;
}
*encrypted = '\0';
return begin;
}
int main()
{
const char plaintext[] = "This is my plaintext.";
char *ciphertext = NULL;
ciphertext = encrypt(plaintext);
std::cout << "Plaintext: \"" << plaintext << "\"" << std::endl;
std::cout << "Ciphertext: \"" << ciphertext << "\"" << std::endl;
delete ciphertext; ciphertext = NULL;
}
请注意,我做了两个重要的更改:
strlen(not_encrypted)
添加一个用于调整encrypted
的大小
buffer(这是为'\ 0'null-terminator字符提供空间
在输出中)和encrypted
。