I'm trying to use a while loop to read in some files, but it only reads once and quits. Not sure what's wrong, professor says this is how it should work as long as I'm understanding him correctly.

void populateStruct(ifstream &filein, WordStruct Words[1000], int &itemamount)
    while (filein >> Words[itemamount].Word);
        Words[itemamount].WordAmt = 1;
        cout << itemamount;

I've tried placing the filein >> command inside the loop as well as it being the condition, but nothing.

4 Years
Discussion Span
Last Post by Secone

If I understand correctly what you are doing, then your professor is correct. The terminating condition of the loop is being able to read words from the input file. If you want to handle multiple files, then in the calling function (the one that calls pupulateStruct()) you will need to close the input file and open the next in another loop, inside of which you would call the populateStruct() function.


It's only one file. I had just opened the file up in the previous function, and then began running this. I'm trying to read all words from the file into the struct.


Then we obviously need more context. Like the function(s) that call this one, the one that opens the file, and the first few lines of the file.

And an exact descripton of what's going wrong with as much detail as you can provide.


What else could you need to know? I opened the file up in the function preceding this one. The file has multiple words in it across various lines. The loop is only reading the first word and then quitting from looping, so when I cout the results it only shows that one item was entered in and only the first word in the file appears. Only main is calling this function.


What else could you need to know?

The contents of the file and enough context to test your code, obviously. For example, how have you defined WordStruct? Please compose a small test program that's complete, then post it here along with a sample of the file you're using. Reproduction of the problem is the first step in troubleshooting.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.