The immediate problem is in these lines:
55 56 57
|
indexY ++ ;
cout << ordArray[indexX][indexY] ;
|
indexY is incremented to the next array position before the cout statement, hence the garbage data from the uninitialised array content. Move the increment after the cout.
Other problems, at line 26 in the overloaded << operator function,
cout <<
should be
output <<
. It's also good practice to make the second parameter
const
, since it will not be changed by the function.
The 2-D array doesn't seem necessary, it could be a simple 1-D array. (Well, in this example no array at all is needed, but I expect it will be used later).
And, it is not a good idea to loop on
eof()
, it can give rise to errors, such as repeating the last line of the file twice. Instead, put the input operation inside the loop condition. Also check that the array size has not been exceeded.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std ;
struct myRecord
{
int OrdNum ;
int day ;
int month ;
int year ;
string color ;
string garbage1 ;
string garbage2 ;
string garbage3 ;
string garbage4 ;
string garbage5 ;
double SqMt ;
double price ;
friend ostream & operator<< ( ostream & output, const myRecord & v)
{
output << v.garbage1 << " " << v.OrdNum << endl
<< v.garbage2 << " " << v.day << " " << v.month << " " << v.year << endl
<< v.garbage3 << " " << v.color << endl
<< v.garbage4 << " " << v.SqMt << endl
<< v.garbage5 << " " << v.price << endl << endl ;
return output;
}
};
int main ()
{
const int arraysize = 10;
myRecord ordArray[arraysize];
int indexY = 0 ;
ifstream orderFile ;
orderFile.open ("orders.txt") ;
while ( (indexY < arraysize) &&
orderFile >> ordArray[indexY].garbage1 >> ordArray[indexY].OrdNum
>> ordArray[indexY].garbage2 >> ordArray[indexY].day >> ordArray[indexY].month >> ordArray[indexY].year
>> ordArray[indexY].garbage3 >> ordArray[indexY].color
>> ordArray[indexY].garbage4 >> ordArray[indexY].SqMt
>> ordArray[indexY].garbage5 >> ordArray[indexY].price )
{
// cout << ordArray[indexY] ; // output deferred until later
indexY ++ ;
}
orderFile.close();
// Now output array contents
for (int i=0; i<indexY; ++i)
{
cout << ordArray[i];
}
system ( "pause" ) ;
return 0 ;
}
|