C++ strcuts and arrays

This is a discussion on C++ strcuts and arrays within the C++ Programming forums, part of the General Programming Boards category; In the following code I am trying to resize the array at the correct place, my teacher said to ask ...

C++ strcuts and arrays

In the following code I am trying to resize the array at the correct place, my teacher said to ask for input for one item of the struct first then use a temp variable and I can't figure this out. thanks.

Code:

if(infile.fail())//begin if-else
cout<<"Sorry, the file could not be opened."<<endl;
else
{
while(!infile.eof())//this while loop resizes the vector and inputs the names from the file until the file ends
{//begin while
infile>>recordList[recordList.length()].sku;
int temp = recordList[recordList.length()].sku;
if(temp != infile.eof())//this if
{//begin if
infile.ignore(2,'\n');
getline(infile,recordList[recordList.length()].artist);
getline(infile,recordList[recordList.length()].album);
infile>>recordList[recordList.length()].quantity;
infile>>recordList[recordList.length()].price;
recordList.resize(recordList.length() + 1);
}//end if
}//end while
}//end if-else

First of all, where is everybody getting the length() method from on these containers? Is that standard? I've never seen it in any reference (including TC++PL). I'm pretty sure that size() is what you want. Second, that is fundamentally incorrect. Because indices start at 0, the recordList.size() element will always be out of bounds. Think about it. I think what your teacher wants you to do, rather than using the resize() method, is to use a temporary structure in tandem with push_back, like this:

Code:

//First, create a temporary structure to hold input
//I don't know what type recordList holds, so I'll guess
Record input;
//You should consider not basing your loop on infile.eof(), it can be squirrely
//Read the FAQ on feof()
while(!infile.eof())//this while loop resizes the vector and inputs the names from the file until the file ends
{//begin while
infile >>input.sku;
if(input.sku != EOF) //This is probably still wrong, but it's closer.
{//begin if <--- WHY THESE COMMENTS? IS INDENTATION NOT ENOUGH?
infile.ignore(2,'\n'); //THIS LINE REALLY ISN'T SAFE
getline(infile, input.artist);
getline(infile, input.album);
infile >>input.quantity >>input.price;
recordList.push_back(input);
}
}
//etc....

to avoid using ignore you can read ALL the input using getline
and then - if needed - extract the data from the readed string using stringstream - there is a lot of samples on the board - how to do this