Read formatted input from a text file. - C++ File Stream

C++ examples for File Stream:Text File

Description

Read formatted input from a text file.

Demo Code

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()//  w ww.java 2s.  c o  m
{
   int i, n;
   double d;
   string str;
   ifstream fin("test.dat");
   if(!fin) {
      cout << "Cannot open file.\n";
      return 1;
   }
   // Read the formatted data.
   fin >> i;
   fin >> n;
   fin >> d;
   fin >> str;
   // Close the input file.
   fin.close();
   // Confirm that no input errors occurred.
   if(!fin.good()) {
      cout << "A file error occurred.";
      return 1;
   }
   // Display the data.
   cout << i << " " << n << " " <<
   d << " " << str << "\n";
   return 0;
}

Result


Related Tutorials