Page 292 - DCAP404 _Object Oriented Programming
P. 292

Unit 13: Working with Files




          getline()                                                                             Notes

          This  function is used to read one line at a time from an input stream until some specified
          criterion is met. The prototype is as follows:
          getline(Array,Array_size,delimiter);

          The stopping criterion can be either specified number of characters (Array_size) or the first
          occurrence of a delimiter (delimiter) else the entire line (up to newline character ‘\n’) is read. If
          you wish to stop reading until one of the following happens:
          1.   You have read 10 characters
          2.   You met the letter ‘m’
          3.   There is new line

          Then the function will be called as follows:
          getline(Carray,10,’m’);
          The use of getline() function is demonstrated in the following example.

          //Demonstration  of  getline()  function  to  read  a  file  line-wise
          #include  <fstream.h>
          void  main()
          {
                 //Assume  that  the  text  contained  in  data.dat  file  is  “Welcome  to
          C++”

                 ifstream  myfile(“data.dat”);
                 static  char  Carray[10];
                 myfile.getline(Carray,10,’m’);
                 cout  <<  Carray  <<  endl;  //the  output  should  be  “Welco”
                 myfile.close();
          }

          peek()

          This function returns the ASCII code of the current character from an input file stream very much
          like get() function, however, without moving the pointer to the next character. Therefore, any
          number of successive call to peek() function will return the ASCII code of same character each
          time. To convert the ASCII code (as returned by peek() function use char type cast) as demonstrated
          in the following code program.
          //Demonstration  of  peek()  function
          #include  <fstream.h>
          void  main()

          {
                 //  Assume  that  the  text  contained  in  data.dat  file  is  “Welcome  to
          C++”
                 ifstream  myfile(“data.dat”);




                                           LOVELY PROFESSIONAL UNIVERSITY                                   285
   287   288   289   290   291   292   293   294   295   296   297