【问题标题】:cout, XOR, and fileIO formatting issues in C++C++ 中的 cout、XOR 和 fileIO 格式问题
【发布时间】:2013-06-27 12:13:57
【问题描述】:

自从我开始使用 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();
}

【问题讨论】:

    标签: c++ file encryption io xor


    【解决方案1】:

    std::ifstreamget() 函数(用于从输入文件中检索字符)在到达文件末尾时返回 eof(文件结尾)。您需要对此进行检查(而不是在循环中检查 ifile.good())。

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

    这是一个简单的循环,它使用get()std::cin 读取字符并将它们回显到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() 来读取更大的块。

    【讨论】:

    • 请注意getLine()在解密部分不起作用,因为加密的结果可能包含各种控制字符。要执行有意义的加密,您应该使用显式字符编码(但同样,您也不应该使用单字符加密,出于测试目的,您应该能够摆脱它)。
    • @owlstead 是的,没错。我以某种方式假设加密仅适用于这里的字母字符,但你是对的,它也会影响行尾。
    • 谢谢!在我检查了 eof 后工作得很好。文件 IO 对我来说一直是个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    相关资源
    最近更新 更多