gpt4 book ai didi

c++ - 为什么我的代码打印出错误的密文?

转载 作者:行者123 更新时间:2023-11-27 23:39:50 26 4
gpt4 key购买 nike

我正在尝试制作一个程序,通过在每个字母前十个字母将字符串转换为加密。 https://gyazo.com/86f9d708c2f02cf2d70dbc1cd9fa9a06我正在做第 2 部分。当我输入“helloworld”时,会出现类似 0x45 的内容。请帮忙!这很快就要到期了!

我试过弄乱 for 循环,但没有帮助。

#include <iostream>

using namespace std;

int main()
{
//Input Message
cout << "Enter a message" << endl;
string message;
getline(cin, message);

//Convert Message to Numbers
int numMess[message.length()];
for (int i = 0; i<message.length(); i++) {
numMess[i] = (int)message[i];
}

cout << numMess << endl;

//Encrypt Number Message by adding ten to each one
int encryptNumMess[message.length()];
for (int a = 0; a < message.length(); a++){
encryptNumMess[a] = numMess[a] + 10;
if (encryptNumMess[a] > 122) {
encryptNumMess[a] = 97;
}
}
cout << encryptNumMess << endl;

//Convert Encrypted Number Message to letters
string encryption[message.length()];
for (int b = 0; b<message.length(); b++) {
encryption[b] = (char)encryptNumMess[b];
}

cout << encryption << endl;
return 0;
}

我希望当我输入“helloworld”时,最终结果将是“rovvygybvn”

最佳答案

如果您愿意放弃手工编码的循环,您可以使用 STL 算法,例如 std::transform要做到这一点:

但首先,您应该做几件事:

不要使用 122、97 等魔数(Magic Number)。而是使用实际的字符常量,即 ab 等。但是如果我们假设 ASCII ,其中字母字符代码是连续的,您的特定程序可以简单地使用常量字符串来表示字母表,然后使用简单的索引来挑选字符。

const char *alphabet = "abcdefghijklmnopqrstuvwxyz";

然后为了得到字母a,一个简单的减法就是得到索引所需要的:

char ch = 'b';
int index = ch - 'a'; // same as 'b' - 'a' == 98 - 97 == 1
std::cout << alphabet[index]; // will print 'b'

鉴于此,接下来的事情是计算出如果将值加 10 到达的是什么字符,如果大于 26,则环绕到字母表的开头。这可以使用模数(除法后的余数)来完成

char ch = 'x';
int index = (ch - 'a' + 10) % 26; // Same as ('x' - 'a' + 10) % 26 == (120 - 97 + 10) % 26 == 33 % 26 == 7
std::cout << alphabet[index]; // will print 'h'

下一步是找出相反的方法,给定一个加密字符,你必须通过减去 10 来找到未加密的字符。这里用相反的方式包装,所以需要做更多的工作(未显示,但代码示例反射(reflect)了所做的事情)。

将所有这些放在一起,并使用 std::transform 和 lambdas,我们得到以下小程序:

#include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
#include <cmath>

int main()
{
//Input Message
const char *alphabet="abcdefghijklmnopqrstuvwxyz";
std::string message = "helloworld";
std::string result;

// set the encrypted string using the formula above and std::transform
std::transform(message.begin(), message.end(), std::back_inserter(result),
[&](char ch) { return alphabet[(ch - 'a' + 10) % 26]; });
std::cout << "Encrypted: " << result << '\n';

// convert back to unencrypted using the above formula and std::transform
std::string result2;
std::transform(result.begin(), result.end(), std::back_inserter(result2),
[&](char ch)
{ int index = ch - 'a' - 10; index = index < 0?26 - (abs(index) % 26):index % 26; return alphabet[index];});
std::cout << "Unencrypted: " << result2;
}

输出:

 Encrypted: rovvygybvn
Unencrypted: helloworld

关于c++ - 为什么我的代码打印出错误的密文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com