C ++中的cout,XOR和fileIO格式问题

时间:2013-06-30 02:01:47

标签: c++ file encryption io xor

我遇到了一些我以前从未见过的问题,因为我开始搞乱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();
}

1 个答案:

答案 0 :(得分:2)

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

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

这是一个简单的循环,使用std::cinget()读取字符,并在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()来阅读更大的块。

相关问题