我有 6 个整数 25 5个 30 6个 20 36 在一个 txt 文件中。程序打开txt文件就ok了。在我的 main 中的“cout for loop”中,程序输出看起来是整数的二进制表示形式。但是,输出文件包含提取的相同整数,而不是二进制数据。我从教科书中得到了这个样本。如何修复它以读入整数并写出二进制整数?
#include "lib.h"
//========================================================================================
//========================================================================================
void open_infile(ifstream& ifs)
{
string infile;
cout << "Please enter the name of the file:";
cin >> infile;
ifs.open(infile.c_str(), ios_base::binary);
if (!ifs) error("can't open out file");
}
//========================================================================================
//========================================================================================
void open_outfile(ofstream& ost)
{
string outfile;
cout << "Please enter the name of the file:";
cin >> outfile;
ost.open(outfile.c_str(), ios_base::binary);
if (!ost) error("can't open out file");
}
//========================================================================================
//========================================================================================
void get_fileContent(ifstream& ifs, vector<int>& v)
{
int i = 0;
while(ifs.read(as_bytes(i),sizeof(int)))
v.push_back(i);
}
//========================================================================================
//========================================================================================
void write_fileContent(ofstream& ost, vector<int>& v)
{
for(int i =0; i < v.size(); ++i)
{
ost.write(as_bytes(v[i]),sizeof(int));
}
}
//========================================================================================
//========================================================================================
int main()
{
ifstream ifs;
ofstream ost;
vector<int> v;
open_infile(ifs);
get_fileContent(ifs, v);
//just checking to make sure data is being copied to int vector correctly
for(int i =0; i < v.size(); ++i)
{
cout<< endl << v[i]<< endl;
}
open_outfile(ost);
write_fileContent(ost, v);
keep_window_open();
}
//========================================================================================
//========================================================================================
main 中 for 循环的输出是: 168637746 856296757 906628400 808585741 909314573
最佳答案
如果你想让你的文件看起来像输出到 stdout,那么你需要像对 cout
一样来写它:
void write_fileContent(ofstream& ost, vector<int>& v)
{
for (int i = 0; i < v.size(); ++i)
{
ost << endl << v[i]<< endl;
}
}
operator<<
做格式化输出,而 write
做未格式化输出。
关于c++ - 该项目不会将整数作为二进制读取并将它们作为二进制输出到新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20805901/