c++ - 打开一个文件,修改每个字符然后做反向操作不输出原始文件

标签 c++ file char fstream

#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/

相关文章:

c++ - 使用属性页数组 MFC C++ 创建无模式属性表

c++ - 错误 : "lvalue required as left operand of assignment"

javascript - 为什么即使调用 evt.preventDefault();,更改 JavaScript 中的内部 html 也会导致默认操作?

java - 字符大小是 8 位还是 16 位?

java - 无法显示循环中的所有字符

c++ - 如何为类生成字典(vector<vector<short>>)

c++ - 矩阵迭代的逐位移位?

c++ - 如何使用 C 或 C++ 获取目录中的文件列表?

java - 打印文件 Java 的行时出现问题

java - java中如何将大于1000的值转换为char