CSC 272 - Software II: Principles of Programming Languages

Dr. R. M. Siegfried

A Program in C++ to Display An Array Of Integers Stored In A Text file


// The first include is for the I/O Stream (console) library
#include	<iostream>

//The second include is for the file stream library
#include	<fstream>
//This enables the use of exit() in Turbo C++
#include	<stdlib.h>

using	namespace	std;

// main() - A program to display a file on the screen
int	main(void)
{
	const int	FileNameLen = 30;	// Constant integer
	ifstream	infile;			// file object
	char		filename[FileNameLen];	// Store the file name
						// as a character string
	char		inchar;		//Read a character at a time


	// Get the file name
	cout << "Enter file name ->" << '\t' ;
	cin >> filename;
	// Open the file
	infile.open(filename);
	// If you can't open the file, print an error message
	//	and quit
	if (!infile)	{
		cerr << "Cannot open " << filename << endl;
		exit(1);
	}

        // Read the file a character 
	while (!infile.eof())	{
		inchar = infile.get();//This reads in
					//even whitespace characters
                cout << inchar;	//Display it on screen
	}
	infile.close();	//Close the file	
	return(0);
}

[Back to the C++ Examples List]