c++中的加密问题
Encryption issue in c++
我目前正在尝试实现一个替换密码,由于某种原因不断崩溃,代码相当直接,但我一直遇到问题,我认为起源于for循环或当我试图从文件中读取数据时。
cout << "Ener a key :";
cin >> key;
cin.ignore();
cout << endl << "Enter input file name: ";
getline(cin,fileIn);
inputfile.open(fileIn.c_str(), ios::in);
cout << endl << "Enter output file name: ";
getline(cin,fileOut);
outfile.open(fileOut.c_str(), ios::app);
cout << endl << "[E]ncryption or [D]ecryption? :";
cin >> EorD;
//Encryption
if (EorD == "E" || "e")
{
while(!inputfile.eof()) // Reading in file data, while not end of file.
{
getline(inputfile,plainText);
}
for (int i = 0; i <= plainText.length(); i++)
{
char letter = plainText.at(i);
int val = (int)letter; // getting ascii value of each letter.
int EnVal = (val - 32) + key;
if(EnVal > 95)
{
EnVal = (EnVal - 95) + 32;
}
char EnLetter = static_cast<char>(EnVal);
outfile << EnLetter;
change
for (int i = 0; i <= plainText.length(); i++)
for (int i = 0; i <= plainText.length()-1; i++)
因为超出范围。使用iterator
更好。
也改变这个:
if (EorD == "E" || "e")
if (EorD == "E" || EorD == "e")
因为前者总是正确的。
正如James Kanze指出的那样,不要使用std::string::at
,你在这里不需要它,将其更改为std::string operator[]
和我的建议:另外在一个漂亮的try{}catch(...){}
块中覆盖你的代码
你可以考虑这样做:
#include <vector>
#include <iterator>
#include <algorithm>
int key=100;
char op(char c){
char letter = c;
int val = (int)letter; // getting ascii value of each letter.
int EnVal = (val - 32) + key;
if(EnVal > 95)
{
EnVal = (EnVal - 95) + 32;
}
char EnLetter = static_cast<char>(EnVal);
return EnLetter;
}
int main(){
try{
std::string s="piotrek";
std::vector<char> vc_in(s.begin(),s.end());
std::vector<char> vc_out;
std::transform (vc_in.begin(), vc_in.end(),
std::back_inserter(vc_out), op); //this do the thing
std::copy(vc_out.begin(), vc_out.end(),
std::ostream_iterator<char> (std::cout,"_")); // to print
}catch(std::exception& e){
cout<<"exception: "<<e.what();
}
return OK;
}
您在plainText
字符串中循环了一个索引太远。因为它有length()
个条目,第一个是0
,最后一个索引是length()-1
。试试这个:
for (int i = 0; i < plainText.length(); i++)
否则i
太大时plainText.at(i)
会崩溃
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 我在 c++ 中的 AES 代码有问题。明文正在更改,但加密邮件是相同的。我找不到我的错误
- 加密蛋白使编译问题Ubuntu
- C ++中的加密和PHP中的解密有什么问题
- Windows 7上运行的QCA(QT C 加密库)的问题
- Mupdf加密解密问题
- 关于RSA加密的各种问题
- 这个加密/解密算法哪里出了问题
- XOR加密问题…总初学者
- c++中的加密问题
- 创建一个有三种方法可供选择的加密程序!它有问题,我不知道如何解决