#include <fstream>
int main()
{
// compress
std::ifstream inFile("test.input");
std::ofstream outFile("test.compressed");
char c;
while(inFile >> c)
outFile << c + 1;
// decompress
std::ifstream inFile2("test.compressed");
std::ofstream outFile2("test.output");
while(inFile2 >> c)
outFile2 << c - 1;
// close
inFile.close();
outFile.close();
inFile2.close();
outFile2.close();
return 0;
}
这是我的代码。可能有一些我不明白的地方,因为对我来说 test.input
应该与 test.output
相同,但它们不是。
最佳答案
这里有两个问题。首先,当您从 int
中添加(或减去)char
时,结果是 int
。所以计算 c + 1
将作为数字写入 test.compressed
(例如,'a'
的 ASCII 码是 97
。因此,在向其中添加 1
后,您将得到 98
,这将作为字符 '9'
写入文件> 和 '8'
)。然后从这些字符中减去 1,显然不会得到相同的输出。这可以通过将结果转换回 char
来解决。
第二个问题更平淡无奇 - 您尝试在刷新之前从您写入的文件中读取它,因此您可能会丢失部分(或全部)您写入的数据。这可以通过在完成文件后关闭文件来解决,这通常是一个很好的做法。
综合起来:
#include <fstream>
int main()
{
// compress
std::ifstream inFile("test.input");
std::ofstream outFile("test.compressed");
char c;
while(inFile >> c)
outFile << (char)(c + 1); // Casting to char
// Close the files you're done with
inFile.close();
outFile.close();
// decompress
std::ifstream inFile2("test.compressed");
std::ofstream outFile2("test.output");
while(inFile2 >> c)
outFile2 << (char)(c - 1); // You need the cast here too
// Close the files you're done with
inFile2.close();
outFile2.close();
return 0;
}
关于c++ - 打开一个文件,修改每个字符然后做反向操作不输出原始文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43819375/