Read Array


Program Listing

ReadArray.cpp

/************************************************************************
*                                                                       *
*   Program:    ReadArray                                               *
*                                                                       *
*   Abstract:   This program will read integers from the file Data      *
*               into an array                                           *
*                                                                       *
************************************************************************/

//  Header files

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

/************************************************************************
*                                                                       *
*   Function:   main                                                    *
*                                                                       *
*   Purpose:    To read integers from the file Data into an array       *
*                                                                       *
************************************************************************/

int main() {

//  Create an array of size 10

    const int maxArraySize = 10;            // Maximum array size
    
    int a[maxArraySize];                    // Create the array

//  Open the file Data

    ifstream fin("MacintoshHD:LectureNotes:Coms_261:Examples:Data");
    
    if (!fin) {
        cerr << "ERROR:  Failed to open file 'Data'." << endl;
        cerr << "Aborting..." << endl;
        exit(1);
    }

//  Read from the file into the array

    int size = 0;                           // Initialize array size
    int value;                              // Value from file

    while ((size < maxArraySize) && (fin >> value)) // Get next value from file
        a[size++] = value;                  // Assign value to array
        
//  Display the array

    for (int i = 0; i < size; i++)
        cout << a[i] << ' ';
        
    return 0;
}

Sample Run

5 15 25 35 45 55 65 75 85 95 



Return to Lectures page


e-mail me at robbk@hsc.edu

This page was last modified on Tue Dec 7 16:04:54 1999 .

URL: http://people.hsc.edu/faculty-staff/robbk/Coms261/Examples/ReadArray.html

Return to Coms 261 home page