【日常踩坑】使用空字符串ciphertext[i]来赋值报错

项目场景:

一道初级练习题如下,

为了使电文保密,最简单的方法就是按照一定的规律将电文转换 成密码,收报人在根据约定的规律将电文译回原文。例如可按照如下规律 将电文编程密码: 对大写字母变成其后面的第四个字母,如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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值