【日常踩坑】使用空字符串ciphertext[i]来赋值报错
生活随笔
收集整理的這篇文章主要介紹了
【日常踩坑】使用空字符串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; }總結
以上是生活随笔為你收集整理的【日常踩坑】使用空字符串ciphertext[i]来赋值报错的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 度小满启动“小微加油站”,让低息服务可持
- 下一篇: 读书|林曦:她把自己的生活,过成了无用但