// File: readAndPrintStruct.cpp // Example of opening, reading, and printing a file of integers // Now, with a struct to hold the data #include #include #include using namespace std; int const MAX=10; // A partially filled array (can have 0 to 10 elements // An array along with an int to store how many items are in use struct Data { int list[MAX]; int items; }; // Opens file designated by user. Returns whether file was opened. // Parameters: // inf import/export bool openFile(ifstream &inf); // Read elements in file and place in array // Parameters: // inf import/export // TheData output only // max Note that with a global const, this parameter is not retained. void readFile(ifstream &inf, Data &TheData); // Print the integers read // TheData import only // Could there be any advantage to passing TheData by reference? void printFileContents(Data TheData); int main() { ifstream inf; Data TheData; if (openFile(inf)) { readFile(inf,TheData); printFileContents(TheData); } } // Opens file designated by user. Returns whether file was opened. // Parameters: // inf import/export bool openFile(ifstream &inf) { string fileName; cout << "Enter File Name >"; cin >> fileName; inf.open(fileName.c_str()); return(inf); // returns true if file found and opened } // Read elements in file and place in array // Parameters: // inf import/export // TheData export only // max Note that with a global const, this parameter is not retained. void readFile(ifstream &inf, Data &TheData) { int value; TheData.items=0; while (TheData.items> value) TheData.list[TheData.items++]=value; } // Print the integers read // TheData import only // Could there be any advantage to passing TheData by reference? void printFileContents(Data TheData) { for (int i=0;i