Page 295 - DCAP404 _Object Oriented Programming
P. 295
Object-oriented Programming
Notes fout.open(“name_age.dat”,ios::app); // open file for appending
assert (!fout.fail( ));
for(i=1; i<=number; i++)
{
cout<<“Enter the name: “;
getline(cin,name);
cout<<“Enter age: “;
cin>>age;
getline(cin,age);
fout<<name<<endl; //send to file
fout<<age<<endl;
}
fout.close( ); //close file
assert(!fout.fail( ));
return 0;
}
13.5 Processing and Closing a File
File processing in C++ is performed using the fstream class. Unlike the FILE structure, fstream
is a complete C++ class with constructors, a destructor and overloaded operators.
To perform file processing, you can declare an instance of an fstream object. If you do not yet
know the name of the file you want to process, you can use the default constructor.
Notes Unlike the FILE structure, the fstream class provides two distinct classes for file
processing. One is used to write to a file and the other is used to read from a file.
This is an example of performing file processing in C++. The following technique can be used to
save complete but separate lines of text using the “ws” feature on Microsoft Windows. This
(undocumented) feature is built-in in the operating system and works on both Microsoft C++
and Borland C++ compilers. I didn’t test this program on Linux (my Linux computer was not
available) but it is not likely to work on that operating system because, as stated already, cin >>
ws which is used to “freely” eat a keyboard stroke is part of MS Windows.
Microsoft Visual C++ Version
#include <fstream>
#include <iostream>
#include <string>
288 LOVELY PROFESSIONAL UNIVERSITY