求高手指点!关于C++中ofstream的write函数的用法?

下面这段程序是C++ How to Program 这本书里的一段程序。目的是创建一个文件并用
write函数写入100条初始记录 “0, "", "", 0.0 ”。
但是我运行的结果都是乱码。 我想是由于下面这条语句的问题。似乎把&blankClient 改成const char *, 就不会正常打印“0, "", "", 0.0 ”? 到底是什么原因产生乱码呢?

outCredit.write( 
reinterpret_cast<const char *>( &blankClient ), 
sizeof( clientData ) );

源程序:
// Fig. 14.11: clntdata.h
// Definition of struct clientData used in 
// Figs. 14.11, 14.12, 14.14 and 14.15.
#ifndef CLNTDATA_H
#define CLNTDATA_H

struct clientData {
int accountNumber;
char lastName[ 15 ];
char firstName[ 10 ];
double balance;
};

#endif

// Fig. 14.11: fig14_11.cpp
// Creating a randomly accessed file sequentially
#include <iostream>

using std::cerr;
using std::endl;
using std::ios;

#include <fstream>

using std::ofstream;

#include <cstdlib>

#include "clntdata.h"

int main()
{
ofstream outCredit( "credit.txt", ios::binary );
//ofstream outCredit( "credit.txt", ios::out );
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}

clientData blankClient = { 0, "", "", 0.0 };

for ( int i = 0; i < 100; i++ )
// outCredit<<blankClient <<"\n";
outCredit.write( 
reinterpret_cast<const char *>( &blankClient ), 
sizeof( clientData ) );
return 0;
}

阿波罗的战车
浏览 432回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP