CSC 272 - Software II: Principles of Programming Languages
Dr. R. M. Siegfried
A Program in C++ to Write An Array Of Integers 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;
// Since you can't define constants inside a class declaration,
// I defined them here
const int FileNameLen = 30, ArrayLen = 20;
// The class array
class array {
public: // These functions are avaiable for use outside the class
array(void);
//Inline functions are compiled into the code of the program
// so they run faster than standard function calls
inline int getsize() {return(size);}
void read(void);
void write(void);
private:
//Private - available only to member functions
int x[ArrayLen];
int size;
};
// An initialization constructor - called automatically
// when an object from this class is defined
array::array(void)
{
size = 0;
}
// Readarray() - Read the array
// Arrays are passed by reference
void array::read(void)
{
size = 0;
// Read each value
do {
cout << "Enter a value\t?";
cin >> x[size++]; // Read an integer
} while (x[size-1] != 0 && size < ArrayLen);
// Array indices run from 0 to n-1
size = (size == ArrayLen)? size - 2: size - 1;
}
void array::write(void)
{
ofstream outfile; // file object
char filename[FileNameLen]; // Store the file name
// as a character string
cout << "Enter file name ->\t";
cin >> filename;
// Open the file
outfile.open(filename);
// If you can't open the file, print an error message
// and quit
if (!outfile) {
cerr << "Cannot open " << filename << endl;
exit(1);
}
for (int i = 0; i < size; i++)
outfile << "x[" << i << "] = " << x[i] << '\n';
}
int main(void)
{
array myarray;
myarray.read();
myarray.write();
return(0);
}
[Back to the C++ Examples List]