ofstream.put();不写整数?

ofstream.put(); not writing ints?

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