Reading a Text File


Before learning this section I hope you know the Difference between void main ( ) and int main ( ). If you haven't seen the section then please do so and come back here. 

The program to read the text file that you created in the previous section is as follows : 

#include <iostream.h>
#include <fstream.h>
int main ( )
{
ifstream in("test.txt");
if(!in)                                            
// If the file doesn't exist then the program will quit.
{
cout<<"File cannot be opened";            
return 1;
}
char string[15];
int num;
in>>string>>num;
cout<<string<<num<<endl;
in>>string>>num;
cout<<string<<num<<endl;
in.close();
return 0;
}

>> is the extraction operator. As you know, it is used for obtaining an input from the keyboard along with the keyword cin (console in). Suppose you declare an integer x. You get the value from the user using the statement : cin>> x ; What the user types is stored in the variable x. Similarly in the above program what does the line in>>string>>num ; do? It reads from the stream in and stores what it read in the variable string and num. The process is as follows :

First of all, the file has been opened. String is a character array. The compiler reads the file (test.txt which has been opened). It reads the first 15 characters. The first word in the file is First. After this it encounters a blank space. Hence the string is terminated (for details on why it doesn't continue reading check the section : Beware of character arrays). Hence the word First is stored in variable array string. Next comes a number. This gets stored in the variable num that you have declared.

Next statement is : cout<<string<<num<<endl;

It just displays on the screen what it read from the file. After this remember that the compiler has reached the end of the first line of the file. It automatically moves to the second line of the file. Hence when we repeat the statement :
in>>string>>num ;
the compiler will read the next line of the file. The process just repeats and Second and 2 are now stored in string and num. Finally, the compiler prints the second line of the file on the screen.


The next section is on : Namespaces and New Style C++ Headers

Go back to the Contents page 2.