下面这段程序是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_Hstruct 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;}
2 回答
- 2 回答
- 0 关注
- 431 浏览
添加回答
举报
0/150
提交
取消