1

自从我开始使用 XOR 运算符和简单的单字符密钥加密以来,我遇到了从未见过的问题。在第二次运行程序后,文本总是在其末尾有一个随机的 ascii 字符。另一个问题是文本“预购”和“后购”在程序每次迭代后交替修改。我敢肯定,这大部分只是由于初学者的错误,尤其是在这些问题出现的方式上缺乏 IO 经验。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    ifstream ifile;
    ofstream ofile;
    string toProc;
    string file;
    char key = ' ';
    cout << "Enter file location: \n";
    cin >> file;
    cout << "Enter key: \n";
    cin >> key;
    ifile.open(file);
    if(ifile.is_open())
    {
        char temp;
        temp = ifile.get();
        toProc.push_back(temp);
        while(ifile.good())
        {
            temp = ifile.get();
            toProc.push_back(temp);
        }

        ifile.close();
    }
    else
    {
        cout << "No file found.\n";
    }
    cout << "Pre action: " << toProc << endl;
    for(int i = 0; i < toProc.size(); i++)
        toProc[i] ^= key;
    cout << "Post action: " << toProc << endl;
    ofile.open(file);
    ofile << toProc;
    ofile.close();
}
4

1 回答 1

2

用于从输入文件中检索字符的get()函数在到达文件末尾std::ifstream时返回eof(end-of-file)。您需要检查这一点(而不是检查ifile.good()循环)。

现在它的编写方式,它将eof作为一个字符并将其附加到字符串中。那(即它的异或版本)是您在输出中得到的有趣角色。

std::cin这是一个简单的循环,它从using中读取字符get()并将它们回显到STDOUT. eof它正确地执行检查。您可以将其放入您的代码中,使用ifile而不是std::cin

#include <iostream>

int main()
{
  char c;
  while ((c = std::cin.get()) != std::istream::traits_type::eof())
    std::cout.put(c);

  std::cout << std::endl;
  return 0;
}

我还应该提到该get()函数逐个字符读取,并且没有任何充分的理由。我会使用getline()read()阅读更大的块。

于 2013-06-30T02:49:28.917 回答