An oddity of cin -- type conversion to bool

The now-familiar cin object has type istream. In fact, it is the only object of that type we've seen up until now. Other than the >>-operator, we haven't used it like we've used other types; we never try any other operations. Oddly enough, objects of type istream can be cast as type bool, which means for example that they can be used in the test condition of a loop or an if-statement. But what does that mean?!?!? Let's look at an example:

int j, k=0;
cin >> j;
while(cin)    // type conversion to bool
{
  k = k + j;
  cin >> j;
}
cout << k << endl;
Now what does this do? Well, if I run this program and enter
1 2 3 4;
... it'll print out 10. What it's done is to compute the sum of the numbers entered, stopping at the ';' ... but why?
Answer: The boolean value represents the state of cin. In particular, Normally, cin is in a good state. However, when cin fails to read in an object of the type you've requested, it goes into a failure state. Once in that state, it doesn't go back to a good state.

So, in our loop:

More often than not, we use the fact that the expression cin >> j is an expression that evaluates to cin (with the side effect of reading into the variable j), to write the above more compactly as follows:

Think of while(cin >> j) as follows:
"while cin >> j succeeds ...".

int j, k = 0;
// cin << j evaluates to cin, which then returns its state
while(cin >> j) 
{
  k = k + j;  
}
cout << k << endl;

Reading from a file: use ifstream type

Sometimes we want to read our input from a file rather than from standard-in. In this case, cin won't help us. However, we can create an istream object that acts just like cin except that it gets its character stream from a file rather than a keyboard. So, let's do the same program as above, but first let's create a file temp with the input for our program.

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

int main()
{
  // Create istream object that reads from file temp
  ifstream fin("temp");           // note: fin has ifstream type

  // Loop and add as long as more int's can be read
  int j, k=0;
  while(fin >> j)                 // note: quite similar to the above code except with cin vs. fin
  {
    k = k + j;
  }

  // Print out the sum k
  cout << k << endl; 
  return 0;
}
A couple of comments follow.

When a file ends

When reading data from a file, we often want to simply read until a file ends. Since there isn't really an obvious analogue to that when reading from the keyboard, we haven't had to deal with anything like this. The idea is this:

If you try to read an object, say an int for example, and the file ends before istream object can read an int, the istream object goes into an error state again - i.e. casting it to a bool would result in the value false.
Note that the above code actually applied this idea as follows:
  
// while fin >> k is succeeds..
// When the file ends, (fin >> k) will fail, so the program will exit the loop  
while (fin >> k)      
{
  sum = sum + k;
}

Closing input file streams

We know how to create an ifstream object that is open for reading to a file. How are input file streams closed? Well, when the ifstream object goes out of scope that variable dies, and this closes the connection to the file. If another ifstream object is created to read from the same file, it starts over at the beginning.
Note: you can close a filestream named fin explicitly at any time as follows:
fin.close()

Reading two files at the same time

Can you read two files at the same time? Yes! Simply create two variables of ifstream type at the same time!

ifstream fin1("in1.txt");
ifstream fin2("in2.txt");

int a1, a2;
while( (fin1 >> a1) && (fin2 >> a2) ) // while reading succeeds..
  cout << "file1:" << a1 << ", file2:" << a2 << endl;
The above code will open in1.txt and in2.txt at the same time and read (and print) an integer from each file.

Writing to a file

Just as reading from a file is not much different from reading from cin, writing to a file is not much different from writing to cout. First, you need to create an object of type ostream like cout, but which sends its output to a file. To do this, you declare a variable of type ofstream.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  // Create ostream object that writes to file outfile
  ofstream fout("outfile");

  // Write 1 through 10 on separate lines
  int i;
  i = 1;
  while(i <= 10)
  {
    fout << i << endl;
    i = i + 1;
  }

  return 0;
}
You don't really have the issue of checking to see if the file is found, since you're trying to create a new file. If there is file of that name already there, it gets obliterated ... oops! A fully featured program might warn the user of this. Can you think of how you might check whether the file outfile already exists?

Opening files when the user provides the filename:

If name is a string object with the name of the file you'd like to open, then

string name;
cin >> name;
ifstream fin(name); 
or

string name;
cin >> name;
ifstream fin; 
fin.open(name);
opens an input stream to that file.

Problems

  1. A simple data-conversion problem. You'd be amazed how often you need to write programs that do nothing more than convert data from one format to another. Write a program that reads in a file (name given by user) that contains points in ordered pair notation, and writes the same points to a file (name also given by user) in gnuplot notation, i.e. one point per line, each point given by x-coordinate tab ('\t') y-coordinate. For a nice small file to test with, we have testin.txt. For a nice big challenge file, we have in.txt.
    a solution.
  2. Census Statistics - The census keeps tables of populations and population densities for all of our states. Each state has its own file giving the names of all cities, towns, and CDP's ("census designated place" - this appears to be census-eese for "other") in that state. For example, take a look at Maryland's geographic census data.