我有这样的代码,根据这个[pdf]加密数据。 1 我遇到的问题是代码产生正确的输出。当我的“猫”的OUTPUTFILE我得到正确的答案,但是如果我在文本编辑器打开该文件,我得到的结果是这样的:C++写入文本文件损坏
0068 6e74 7264 727a 0073 7558 6569 7965 0061 6779 686f 6570 0064 6d62 6465 6358 0074 7265 6568 6168 0075 7058 5862 7469 0065 6e72 6d65 676c 0073 6377 6864 6e6f 0073 6d6e 7479 7465 006c 6775 5869 6561
预期输出是:
hntrdrzsuXeiyeagyhoepdmbdecXtreehahupXXbtienrmeglscwhdnosmntytelguXiea
使用这个字符串作为原始的参数和键:玉米片和黑马
sendresupplytothebridgebythechurchXXammoneededurgentlywithmagazinesXXX
这是一个记忆的问题,是我流失败?我觉得我正在俯视一些我什么都看不到的东西。
这是怎么加密:
string encrypt(string &key, string &toEncrypt)
{
int height= 1;
string result = "";
vector<vector<char> > matrix(key.length(), vector<char>(2));
string::iterator it=toEncrypt.begin();
for (int i = 0; i < key.length(); i++)
{
matrix[i][0] = key.at(i);
}
// put info into matrix
printf("%s\n", key.c_str());
while(it!=toEncrypt.end()) // while string still has more chars
{
//printf("newline----\n");
for (int col = 0; col < key.length(); col++,it++)
{
if (it != toEncrypt.end())
{
if(*it == '\0'){it++;}
matrix[col].push_back(*it);
printf("%c", *it);
continue;
}
if(col < key.length())
matrix[col].push_back('X');
printf("%c", 'X');
}
height++;
printf("\n");
}
//parse trough the matrix
printf("\n");
BubbleSort(matrix);
printf("\n");
printf("PAST BUBBLE SORT\n");
for (int c = 0; c < key.length(); c++)
{
for (int r= 1; r < matrix[0].size(); r++)
{
result += matrix[c][r];
printf("%c",matrix[c][r]);
}
printf("\n");
}
printf("THE RESULT IS%s\n", result.c_str());
return result;
}
这是我如何写入文件:
string file = "\0";
printf("Please Enter the name of the file that contains the text to be encrypted with the extention.\n");
getline(cin, file, '\n');
string line;
string encrypted;
transposition_encr encryptor = transposition_encr(k1,k2);
ifstream myfile (file.c_str());
if (myfile.is_open())
{
while (getline (myfile,line))
{
encrypted += line;
}
myfile.close();
}
else
{
cout << "Unable to open file\n";
return -1;
}
cout << encrypted << endl;
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
cout<< encrypted << endl;
encrypted = encryptor.encryption(line);
cout<< encrypted << endl;
string str = "outputfile-encrypted-str.txt";
ofstream myfile2(str.c_str());
if (myfile2.is_open())
{
myfile2 << encrypted;
myfile2.close();
}
// else cout << "Unable to open file\n";
这里是一个link的代码
您如何看待输出? –
输出应该是这个使用键:CORNFLAKES和BLACKHORSE hntrdrzsuXeiyeagyhoepdmbdecXtreehahupXXbtienrmeglscwhdnosmntytelguXiea它与pdf中的相同。 – jcjunction
我应该提到加密方法被调用两次并将结果从一个字符串传递到下一个调用中 – jcjunction