Im trying to read a set a data from text file in a structure array.
However my code works fine with all the other data pass the first one where it reading 0001 instead of 10001
Because your ignore is at the start of the loop, not the end.
1 2 3 4 5 6 7
for (int i = 0; i < 10 && inFile.getline(product[i].num, 6) ; i++)
{
inFile.getline(product[i].des, 31);
inFile >> product[i].price;
inFile.ignore();
count++;
}
1. Always include a loop limiter if you're reading into an array.
2. eof() is a tricky thing to use right (you weren't).
For example, if your file has exactly one line, and you read that line using getline(), then eof() is still false.
eof() only becomes true when some prior getline/get/>> operation has failed.
i dont quite understand the condition of the for loop. Why do i need to add another condition and not just i < 10 ? And why we do not need to read any more product[i].num within the for loop ? Does it get read automatically each time when it is checking the condition ?
> Does it get read automatically each time when it is checking the condition ?
Yes.
Well it's read only if the i<10 part is true.
If i<10 is false (and your array is full), then the right hand side of the && is not evaluated at all.
Otherwise, you end up with something messier like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
for (int i = 0; i < 10 ; i++)
{
if ( inFile.getline(product[i].num, 6) )
{
// pedantically, every input should be checked for success
inFile.getline(product[i].des, 31);
inFile >> product[i].price;
inFile.ignore();
count++;
}
else
{
// no more data
break;
}
}
Now i did try do something as u did there without checking where my for loop only has a condition of i < 10. If somehow the data from the file is inusufficient then is it the reason on why the restover of the array is filled with some random number and data ?