Page 266 - DCAP404 _Object Oriented Programming
P. 266
Unit 12: Console I/O
4. This program demonstrates the reading of data files containing comments and displaying Notes
them on the screen. The lines in the input file starting with ‘!’ will be treated as comment
line. The input file name is comments.txt having the following sample data:
!
! These comment lines should be ignored.
!
This is the first non-comment line.
This is the second non-comment line.
Almost done.
This is the last non-comment line.
// Included files.
#include <iostream> // Header for console I/O
#include <fstream> // Header for file I/O.
#include <string> // Header for STL strings.
// Define skip_comments function.
int skip_comments(ifstream& file, char mark)
{
/*
This function skips the all the lines at the start of the specified
file that begin with the specified character. The file must already be
open when this function is called. Error checking not yet included.
*/
const int MAX_CHARS = 100; // This is the maximum characters per line.
while (file.peek() == mark)
{
file.ignore(MAX_CHARS, ‘\n’);}
return 0;
}
//main function
int main()
{
// Open input file.
ifstream fin; // Declare an input file object.
fin.open(“comments.txt”, ios::in); // Open the input file in project
//folder.
if (!fin) // See if the file was opened successfully.
{
cout << “Can’t open input file. \n”;
return 1;
LOVELY PROFESSIONAL UNIVERSITY 259