tkjordantk
Programmer
- May 19, 2008
- 5
The following code works as expected. It reads data from the input file into the array and displays the array. The problem is that my error checking mechanism "if(!fin.good())" is executing and I'm not sure why...
The file I'm reading from is a simple plain text file (formatted data) with:
5 5.35
15 5.5
30 5.75
The file I'm reading from is a simple plain text file (formatted data) with:
5 5.35
15 5.5
30 5.75
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// Variables where we will store the data read from the file
double myArray[3][2];
// Creates an ifstream object (fin) and tries to open the file data.dat
ifstream fin("data.dat");
// Checks to see if the file was opened correctly
if(!fin)
{
cout << "Can't open file.\n";
return 1;
}
// Reads the data into variables
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 2; j++)
{
cout << "Reading value [" << i << "][" << j << "] - ";
fin >> myArray[i][j];
cout << myArray[i][j] << "\n";
}
}
// Closes the file
fin.close();
// Make sure there were no problems
if(!fin.good())
{
cout << "We have a problem.\n";
return 1;
}
// Print the data to the screen
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 2; j++)
{
cout << "Var[" << i << "][" << j << "] = " << myArray[i][j] << "\n";
}
}
return 0;
}