我编写了一个程序,它读取一个文件,写入另一个文件并打印到屏幕上。换句话说,它应该做三件事(即读、写和打印)。
该程序还应该计算名为“Chap_11_employee_data.txt”的文件中的记录数。但是,它只是显示以下内容。
**Total Records 0**
The End
当它写入文件时,它还会显示奇怪的数字,例如 -858993460。我几乎尝试了所有方法,这导致我在这里注册了一个帐户。下面列出了我的代码以及我试图读取的文件和我试图写入的文件。
非常感谢你的家伙的时间。
代码:
#include <iostream>
#include <fstream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::setw;
using std::ios;
using std::ifstream;
using std::ofstream;
const int EMPLOYEES = 20;
const int MAX = 21;
int ReadData( ifstream &inFile, ofstream &outFile, char name[][MAX], int age[] );
void WriteOutputFile( ofstream &outFile, char name[ ][MAX], int age[ ], int counter );
void PrintTotalsAndSummary( ofstream &out, int totalRecords );
int main()
{
char name[EMPLOYEES][MAX];
int age[EMPLOYEES];
int record_counter(0);
ifstream inFile;
ofstream outFile( "Chap_11_Report.txt" );
inFile.open( "Chap_11_employee_data.txt" );
if ( inFile.is_open() )
{
record_counter = ReadData( inFile, outFile, name, age );
inFile.close();
if( outFile.is_open() )
{
WriteOutputFile( outFile, name, age, record_counter );
PrintTotalsAndSummary( outFile, record_counter );
outFile.close();
}
else
{
cout << "Trouble Opening File";
cout << "\n\n\t\t ** About to EXIT NOW! ** ";
}
}
else
{
cout << "Trouble Opening File";
cout << "\n\n\t\t ** About to EXIT NOW! ** ";
}
return 0;
}
int ReadData( ifstream & inFile, ofstream & outFile, char name[][MAX], int age[] )
{
int counter = 0;
inFile >> name[counter] >> age[counter]; // Priming Read
while ( !inFile.eof() )
{
cout << setiosflags( ios::left ) << setw( 25 )
<< name[counter] << resetiosflags( ios::left )
<< setw( 4 ) << age [counter] << endl;
counter++;
inFile >> name[counter] >> age[counter];
}
return counter;
}
void WriteOutputFile( ofstream &outFile, char name[][MAX], int age[], int counter)
{
outFile << " Here is the Output File" << endl;
for ( int r = 0; r <= counter; r++ )
{
outFile << setiosflags( ios::left ) << setw( 25 )
<< name[r] << setw( 4 )
<< resetiosflags( ios::left ) << age[r]
<< endl;
}
}
void PrintTotalsAndSummary( ofstream &outFile, int totalRecords )
{
// To screen
cout << "\n\n\t** Total Records: " << totalRecords << " **\n"
<< "\t\t The End \n";
// To file
outFile << "\n\n\t** Total Records: " << totalRecords << " **\n"
<< "\t\t The End \n";
}
我正在阅读的文件(Chap_11_employee_data.txt):
"Alexis","Blough",1-1921,"CEO"
"Bill","Pay",1-7711,"Accounting"
"Willy","Makit",4-1595,"Sales"
"Marie","Murray",1-4986,"MIS"
"Cal","Caldwellowinski",5-0911,"MIS"
"Jamie","Johanasola",5-9999,"Marketing"
我正在写的文件(Chap_11_Report.txt):
Here is the Output File
-858993460
** Total Records: 0 **
The End