Examples of Reading Data from an Input file

 

//Example 1: read input from the keyboard

#include <iostream>

using namespace std;

int main()

{

     int x;

 

     cin >> x;            // This will read from the keyboard

     cout << x << endl;   // This will write to the screen

     return 0;

}

 

// Example 2: read input from an input file

#include <iostream>

#include <fstream>

using namespace std;

ifstream infile("in2.dat");

int main()

{

     int x;

 

     infile >> x;          // This will read from the file

     cout << x << endl;    // This will write to the screen

     infile.close();

     return 0;

}

 

// Example 3: read input from an input file till input failure

// using a structured read loop

// also writes to an output file

#include <iostream>

#include <fstream>

using namespace std;

ifstream infile("in3.dat");

ofstream outfile("ex3.out");

int main()

{

     int x;

 

 

     infile >> x;                // This will read from the file

     while(infile) {

          outfile << x << endl;  // This will write to outfile

          infile >> x;           // This will read from the file

     }

     infile.close();

     outfile.close();

     return 0;

}