Page 267 - DCAP404 _Object Oriented Programming
P. 267
Object-oriented Programming
Notes }
cout << “About to skip comments.\n”;
skip_comments(fin,’!’);
string sometext;
getline(fin, sometext);
while (!fin.fail())
{
cout << sometext << ‘\n’;
getline(fin, sometext);
}
if (fin.fail() && !fin.eof())
{
cout << “Error while reading file. \n”;
fin.close();
return 2;
}
return 0;
}
The put() and get() Functions
The classes istream and ostream define two member functions get() and put() respectively to
handle the single character input/output operations. There are two types of get() functions. We
can use both get(char*) and get(void) prototypes to fetch a character including the blank space,
tab and the newline character. The get(char*) version assigns the input character to its argument
and the get(void) version returns the input character. . .
Since these functions are members of the input/output stream classes, we must invoke them
using an appropriate object. For instance, look at the code snippet given below:
char c;
cin.get(c); //get a character from keyboard and assign it to c
while (c!= ‘\n’)
{
cout << c; //display the character on screen cin.get (c);
//get another character
}
This code reads and displays a line of text (terminated by a newline character). Remember, the
operator> >can also be used to read a character but it will skip the white spaces and newline
character. The above while loop will not work properly if the statement.
cin >> c;
is used in place of
260 LOVELY PROFESSIONAL UNIVERSITY