gpt4 book ai didi

c++ - c++中的加密问题

转载 作者:行者123 更新时间:2023-11-27 23:16:04 29 4
gpt4 key购买 nike

我目前正在尝试实现一个由于某种原因不断崩溃的替代密码,代码相当简单,但我一直遇到我认为起源于 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;

最佳答案

改变

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(...){} block 中覆盖您的代码

你可能会考虑这样的事情:

#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;
}

关于c++ - c++中的加密问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16319086/

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