[英]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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.