c ++为什么这个循环有缺陷读取数据到一个struct数组?

c ++为什么这个循环有缺陷读取数据到一个struct数组?

问题描述:

我正在阅读歌曲标题,歌手和歌曲大小。但它只是在第一集中阅读,之后,它给我疯狂的错误的价值观。我的代码是非常简单和直接的,所以我想知道是否有人可以给我一个想法,转向。

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);
}


for 时, i size 循环开始。或者,更正确的是,不会开始: - )

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.