Use get() and getline() to read characters from text file. - C++ File Stream

C++ examples for File Stream:Text File

Description

Use get() and getline() to read characters from text file.

Demo Code

#include <iostream>
#include <fstream>
using namespace std;
int main()/*from   w  ww.  jav  a 2s  .  c  om*/
{
   char ch;
   char str[256];
   ofstream fout("test.dat");
   if(!fout) {
      cout << "Cannot open file for output.\n";
      return 1;
   }
   // Write to the file.
   fout << "This is a line of text.\n";
   fout << "This is another line of text.\n";
   fout << "This is the last line of text.\n";
   fout.close();
   if(!fout.good()) {
      cout << "An error occurred when writing to the file.\n";
      return 1;
   }
   // Now, open the file for input.
   ifstream fin("test.dat", ios::in);
   if(!fin) {
      cout << "Cannot open file for input.\n";
      return 1;
   }
   cout << "Use get():\n";
   // Get the first three characters from the file.
   cout << "Here are the first three characters: ";
   for(int i=0; i < 3; ++i) {
      fin.get(ch);
      cout << ch;
   }
   cout << endl;
   // Now, use get() to read to the end of the line.
   fin.get(str, 255);
   cout << "Here is the rest of the first line: ";
   cout << str << endl;

   fin.get(ch);
   cout << "\nNow use getline():\n";


   fin.getline(str, 255);
   cout << str << endl;
   fin.getline(str, 255);
   cout  << str;
   fin.close();
   if(!fin.good()) {
      cout << "Error occurred while reading or closing the file.\n";
      return 1;
   }
   return 0;
}

Result


Related Tutorials