C++ Notes: Summary of Input / Output

Include files

There are several standard C include files that are commonly used with I/O.
   #include <iostream>  // use for cin and cout
   #include <fstream>   // use for file I/O
   #include <iomanip>   // use for I/O manipulators

Predefined I/O Streams

cinInput stream
coutOutput stream
cerrError message stream
clogBuffered error message stream

Stream Input - cin

  cin >> n;  // reads number into n
A common way to read until an EOF is with a while loop. The value of the input expression will be true if the reads succeeds, and false if it fails. Two possible reasons for failure would be (1) EOF - End of File, and (2) Bad input (eg, non-numeric characters in a number). An EOF can be made on the keyboard with control-D and sometimes this must be followed by a carriage return.
   while (cin >> n) {
      . . .
   }

Stream Output - cout

Stream output to the ostream variable cout uses the << (insertion) operator.
   cout << "Hello World" << endl;

Reading characters and lines from the input stream

  char c;
  cin.get(c);  
  
  string s;
  cin.getline(s);  // reads line (without newline char) into s

Text File Input

You must include <fstream>, declare the file variable, and open the file. Then you can use the ifstream the same as cin.

The open function is used to connect in input or output stream with a file. The parameter is a c-string (char*, not a string). The ifstream/ofstream will have the value NULL if the open was not successful (eg, the file doesn't exist).
  // Read and add all the numbers from the file testdata.txt.
  #include <fstream>
  using namespace std;
  
  void main() {
     ifstream readme;
     int sum, n;
     readme.open("C:\\temp\\testdata.txt");
     if (!readme) {
        // Unable to open file for output (eg, readonly, no disk space)
        cerr << "Unable to open file";
        return 1;
     }
     
     sum = 0;
     while (readme >> n) {
       sum += n;
     }
     cout << "Total: " << sum;
  }

Manipulators

See summary of Output Manipulators for controlling formating of output.
E-mail comments to Fred Swartz (fred@leepoint.net)