c++ why is this loop flawed to read in data to a s

2019-09-15 03:14发布

问题:

I'm reading in a song title, artist, and size of song. but it's only reading in the first set, after that it gives me crazy wrong values. My code is pretty simple and straight forward so I'm wondering if anyone can give me an idea of where to turn.

struct Songs
{
    string title;
    string artist;
    int men;
};
// main stuff

Songs song[50];
int size=0;

for (int i = 0; i<size;i++)
{
    do
    {
        getline(fin, song[size].title);
        getline(fin, song[size].artist);
        fin >> song[size].mem;
        size++;
        i++;
    }
    while (song[size].title.length()>0);
}

回答1:

That code shouldn't do anything since both i and size are zero when the for loop starts. Or, more correctly, doesn't start :-)

If you want to read triplets from your input stream until either a blank title or your array is full, you can start with something like:

// Initialise size.

int size = 0;

// Try to get first title.

getline (fin, song[size].title);

// While a title was successfully read.

while (song[size].title.length() > 0) {
    // Get artist and mem (watever that is).

    getline (fin, song[size].artist);
    fin >> song[size].mem;

    Move to next array element, prevent overflow by loop exit.

    if (++size == 50)
        break;

    // Try to get next title.

    getline (fin, song[size].title);
}

// Out here, size is the number of array elements used (0-50).

It may not compile perfectly, I haven't tested it. It certainly won't handle edge cases like the final triplet only having a title for example. It's meant only to illustrate the algorithm.



回答2:

There are numerous errors in the code.

1) You are setting size to 0, then attempting to start a for loop that won't run because of this.

2) You have a do-while loop within your for loop that appears to be unnecessary for the task you're trying to do if I understand it correctly.

3) When attempting to populate the structs, you use the size variable as the array index. Normally you'd use the iterator variable that you set when you initialise the for loop, in this case i. You should not be incrementing size concurrently with i, either, since you could end up with an endless loop.

4) You don't have indented code! Not exactly an error, but it makes things much harder to debug - and could be part of the reason you're struggling in the first place. (EDIT: appears this has been corrected, now.)

Generally speaking, if you're reading out of a file, one method would be to have an integer at the beginning of the file which specifies the amount of objects you're creating, enabling you to allocate an appropriate amount of memory to the heap, while also setting your size variable. Then you implement a for loop using this size variable to read the data into the structs.



回答3:

Not the least would be while (song[size].title.length()>0) is looking at song[size] after size has already increased. Try song[size-1].