打开一个文件,修改每个字符,然后执行反向操作不输出原始文件


#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;
}

最新更新