I/O Operations in C++

Header files iostream and fstream declare the

istream, ostream, ifstream, and ofstream I/O classes.

Standard Input

  • cin is object representing standard input
  • cin.get (someChar) ; cin.ignore (100, ‘\n’)
  • also use operators cin <<
  • can all use read() function from C

Standard Output

  • cout is object representing standard output
  • cout.write()
  • also use operator cout >>

Example Program using iostream

 

#include <iostream>
using namespace std;

 

int main( )
{                   // USES KEYBOARD AND SCREEN I/O
      using namespace std;
       int partNumber;
       float unitPrice;

       cout << “Enter part number followed by return : “
              << endl ;     // prompt
        cin >> partNumber ;
        cout << “Enter unit price followed by return : “
                << endl ;
        cin >> unitPrice ;
        cout << “Part # “ << partNumber        // echo
                << “at Unit Cost: $ “ << unitPrice << endl ;    

        return 0;
}

 

File I/O

 

  • #include <fstream>
  • choose valid variable identifiers for your files and declare them
  • open the files and associate them with disk names
  • use your variable identifiers with >> and <<
  • close the files

code snipet: opening/clsosing File I/O streams

#include <fstream>

using namespace std;

ifstream myInfile; // declarations
ofstream myOutfile;

myInfile.open(“A:\\myIn.dat”); // open files
myOutfile.open(“A:\\myOut.dat”);


myInfile.close( ); // close files
myOutfile.close( );

 

Sample code

#include <fstream>



int main( )
{ // USES FILE I/O

   using namespace std;

   int partNumber;
   float unitPrice;
   ifstream inFile; // declare file variables
   ofstream outFile;

   inFile.open(“input.dat”);      //open files
   outFile.open(“output.dat”);

   inFile >> partNumber ;

   inFile >> unitPrice ;

   outFile << “Part # “ << partNumber          // echo
              << “at Unit Cost: $ “ << unitPrice << endl ;

   return 0;

}

 

Stream Failure

  • When a stream enters the fail state, further I/O operations using that stream are ignored. But the computer does not automatically halt the program or give any error message.
  • Possible reasons for entering fail state include:
    • invalid input data (often the wrong type),
    • opening an input file that doesn’t exist,
    • opening an output file on a diskette that is already full or is write-protected.

      Program to check for Stream Errors

      #include <fstream>
      #include <iostream>

      using namespace std;

      int main( )
      {     // CHECKS FOR STREAM FAIL STATE

           ifstream inFile;

           inFile.open(“input.dat”); // try to open file

           if ( !inFile )
               { cout << “File input.dat could not be opened.”;
                   return 1; }

       

      . . . return 0;
      }