I'm having trouble figuring out this error.I'm reading an array from a file and displaying to the screen. My .dat file is as follows:
20
12
40
30
30
15
// This program reads employee information from a file and stores them
// in an int array. It uses one for loop to input the hours and another
// for loop to display them.
#include<iostream>
#include<fstream>
usingnamespace std;
int main()
{
constint NUM_EMPLOYEES = 6; // Sets number of employees
int hours[NUM_EMPLOYEES]; // Holds each employees hours
int count; // Loop counter
ifstream datafile; // used to read data from file
// Open data file
datafile.open("work.dat");
if (!datafile)
cout << "Error opening the data file\n";
else
{ // Input hours worked by each employee
for (count = 0; count < NUM_EMPLOYEES; count++)
datafile >> hours[count];
datafile.close();
// Display the contents of the array
cout << "The hours worked by each employee are\n";
for (count = 0; count < NUM_EMPLOYEES; count++)
{ cout << "Employee " << count+1 << ": ";
cout << hours[count] << endl;
}
}
return 0;
}
Here is my output:
The hours worked by each employee a
Employee 1: -858993460
Employee 2: -858993460
Employee 3: -858993460
Employee 4: -858993460
Employee 5: -858993460
Employee 6: -858993460
Press any key to continue . . .
Hi I couldn't see any error in your code so i copied it into my IDE and compiled it and it worked fine. What i think might be the problem is the formatting in your work.dat file. What program are you using to create it?
You're not supposed to give it a different name, you're supposed to save it in plain text format.
Just use a different editor that only supports plain text.