Thread: C++ strcuts and arrays

  1. #1
    Registered User
    Join Date
    May 2007

    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.

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

  2. #2
    Registered User
    Join Date
    May 2007
    int temp = recordList[recordList.length()].sku;
    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:

    //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;
    Hope this helps.
    Last edited by UMR_Student; 05-15-2007 at 09:59 PM.

  3. #3
    "I Win!" by U. Lose vart's Avatar
    Join Date
    Oct 2006
    Rishon LeZion, Israel
    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
    To be or not to be == true

Popular pages Recent additions subscribe to a feed