我正在尝试以一种非常简单的方式加密文件。例如,将文本 aabcdee
转换为 a2bcde2
。
但是,当我执行该文件时,我在输出文件中得到的是 a^Cbcde^C
而不是 a2bcde2
。
我猜 ofstream.put();
不会将整数写入文件?我该如何以正确的方式做到这一点?
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream input;
ofstream output;
char kar;
input.open ("file.txt", ios::in);
if ( ! input)
{
cout << "File not opened!" << endl;
return 1;
}
output.open ("output.txt", ios::out);
char prevkar = '\n';
kar = input.get ();
int rep = 1;
while ( ! input.eof () )
{
if (kar == prevkar)
{
rep++;
kar = input.get();
}
else
{
if (rep > 1)
{
output.put(rep);
}
output.put (kar);
prevkar = kar;
kar = input.get ();
}
}
input.close ();
output.close ();
return 0;
}
最佳答案
在
output.put(rep);
您正在将 rep
作为字符输出。因此,显示的是具有 rep
整数值的任何字符。在本例中是 ^C
。如果你想输出 rep
的实际值,那么你应该使用 >>>
output >> rep;
你也可以使用
output.put('0' + rep);
这只适用于输出 0-9
关于c++ - ofstream.put();不写整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32924244/