Read formatted data from a file. : File Read « File « C++






Read formatted data from a file.

  
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
  int i, n;
  double d;
  string str;

  ifstream fin("test.dat");

  if(!fin) {
    cout << "Cannot open file.\n";
    return 1;
  }

  fin >> i;
  fin >> n;
  fin >> d;
  fin >> str;

  fin.close();

  if(!fin.good()) {
    cout << "A file error occurred.";
    return 1;
  }
  cout << i << " " << n << " " << d << " " << str << "\n";
  return 0;
}
  
    
  








Related examples in the same category

1.Write char to a fileWrite char to a file
2.Read file contentRead file content
3.Demonstrate gcount().Demonstrate gcount().
4.Use getline() to read a string that contains spaces.Use getline() to read a string that contains spaces.
5.Demonstrate peek() in ifstreamDemonstrate peek() in ifstream
6.Demonstrate seekg().
7.Write unsigned char to a file and read it back