Thursday, December 13, 2012
C++ TUTORIAL FOR BEGINNERS: How to read a file and store the records in a character array
The program works as follows:
- database.txt must have records to read input from
- the main () function calls the function read_database_file
- the program opens the "database.txt" input file for reading
- while condition is used to keep on reading while it's not yet end of the file
- if a record is read, the >> operator is used to store the record in a character array (declared as char database_record [256];)
- cout command is used to display on the screen the contents of the character array ( char database_record [256] )
Source code:
#include<iostream>
#include <string>
#include<fstream>
using namespace std;
#define newline '\n'
char database_record [256];
void read_database_file ()
{
ifstream database_file;
database_file.open ("database.txt");
if (database_file.is_open())
{
while (!database_file.eof())
{
database_file >> database_record;
cout << database_record << endl;
}
}
else
{ cout << "Input file not successfully opened.";
database_file.close();
}
}
int main()
{
read_database_file ();
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment