c++ - ofstream.put();不写整数?

标签 c++ file-io output

我正在尝试以一种非常简单的方式加密文件。例如,将文本 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/

相关文章:

c# - Windows 电话 8 : Media file access

C++ 意外数字输出

c++ - 在 range v3 库中,为什么 ranges::copy 不适用于 ranges::views::chunk 的输出?

c++ - 程序终止时,仪器不会捕获未删除的对象

perl - 如何使用 Perl 提供大文件以供下载?

mySQL TSV infile 重复条目

java - 如何使用 SnakeYaml 写入 YAML 文件?

powershell - 如何在Powershell中通过管道传输.exe执行的所有输出?

c++ - 重新定义自定义删除

c++ - gdb 7.0 警告 : Wrong size fpregset in core file