Section 2 - Input Streams

9B.2.1 Opening Input File Streams

These are the header files you'll need in most programs that read/write to files:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

Make sure they are at the top of your current project.

Opening a file for input is easy:

ifstream infile("myInputFile.txt");

As you can guess, this is an instantiation of an ifstream object which we are naming infile.  Also, we are passing the string "myInputFile.txt" to the constructor of this object.  This results in the variable infile being associated with the file "myInputFile.txt" for the duration of this method (or in other methods if you pass the infile as an argument to them, or if infile is a member of a class and other methods of that class want to access it).

What could go wrong?  This:

If you saved the file as I instructed, then neither of these things will happen.  Still, we must test to see if the ifstream was successfully opened, and to do that we test infile for null or non-null:

if (!infile)
{
  cout << "couldn't open myInputFile.txt for input.\n";
  exit(1);
}

In my program, I'm exiting in case of failure, but only after displaying a message.  You will have to do this, too, because for the first few runs of your program, you will probably have this error exit.  You'll need to either fix the name or the location of the file before it will open willingly.

9B.2.2 Reading Data From File Streams

The safest way to read data from a text file is by treating each line as a string.  Create a string buffer and read the line into that buffer with getline():

// read 1st line from file and store into string name
getline(infile, line);

From this point on, you can work with the line as you would any string.  If you want to assign it to another string, use a simple assignment:

name = line;

If you believe it contains numeric data, convert its contents to numbers as you learned, using istringstream:

istringstream(line) >> x >> y;

This is all the input machinery we need at this point.  We next learn how to process and send that information back to a file.