项目场景:
一道初级练习题如下,
为了使电文保密,最简单的方法就是按照一定的规律将电文转换 成密码,收报人在根据约定的规律将电文译回原文。例如可按照如下规律 将电文编程密码: 对大写字母变成其后面的第四个字母,如A->E,W->A; 小写字母变成其后的第3个字母,如a->d,x->a。 请根据题意,编写代码实现将原文变为密码的功能。
问题描述
ciphertext无法输出
if (plaintext[i] + 3 > 'z')
{
ciphertext [i]= ('a' - 1 + (plaintext[i] + 3) % 'z');
}
原因分析:
空字符串不能用ciphertext[i]的方式来赋值
使用了ciphertext[i]来赋值,但是ciphertext并没有在初始化时分配空间或初始化为特定大小,所以ciphertext[i]并没有可以修改的空间,因此会报错。
解决方案:
解决方法之一是使用push_back()函数来将字符添加到ciphertext的末尾,如:
ciphertext.push_back('A'+plaintext[i]%90);
还可以使用+=运算符来添加字符到ciphertext末尾, 如
ciphertext += 'A'+plaintext[i]%90;
完整代码如下
#include <iostream>
#include <string>
using namespace std;
void fun01();
int main()
{
fun01();
return 0;
}
void fun01()
{
string plaintext;
string ciphertext;
cout << "please enter the plaintext" << endl;
cin >> plaintext;
for (int i = 0; i < plaintext.length(); i++)
{
if (plaintext[i] >= 'A' && plaintext[i] <= 'Z')
{
if (plaintext[i] + 4 > 'Z')
{
ciphertext += ('A' - 1 + (plaintext[i] + 4) % 'Z');
}
else
{
ciphertext += plaintext[i] + 4;
}
}
if (plaintext[i] >= 'a' && plaintext[i] <= 'z')
{
if (plaintext[i] + 3 > 'z')
{
ciphertext += ('a' - 1 + (plaintext[i] + 3) % 'z');
}
else
{
ciphertext += plaintext[i] + 3;
}
}
}
cout << "ciphertext=" << ciphertext << endl;
}