0

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

2 回答 2

2

改变

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;
}
于 2013-05-01T13:46:10.097 回答
2

plainText您在字符串中循环一个索引太远。因为它有length()条目并且第一个是0,所以最后一个索引是length()-1。尝试这个:

for (int i = 0; i < plainText.length(); i++)

否则太大plainText.at(i)时会崩溃。i

于 2013-05-01T13:38:06.980 回答