使用文本文件中的数据初始化对象数组

Mik*_*e55 1 c++ arrays initialization file

当我尝试在Visual C++ 2008 Express上编译下面的代码时出现系统错误.我要做的是用文件读取数据初始化对象数组.我认为while循环中有一些错误,因为当我手动初始化这些对象时没有while循环它似乎工作.这是代码和文本文件:

#include <iostream>
#include <string>
#include "Book.h"

using namespace std;            

int main()
{
    const int arraySize = 3;
    int indexOfArray = 0;

    Book bookList[arraySize];
    double tempPrice;//temporary stores price
    string tempStr;//temporary stores author, title


    fstream fileIn( "books.txt" );

    while ( !fileIn.eof( ))
    {
        getline(fileIn,tempStr);
        bookList[indexOfArray].setAuthor(tempStr);

        getline(fileIn,tempStr);
        bookList[indexOfArray].setTitle(tempStr);

        fileIn >> tempPrice;
        bookList[indexOfArray].setPrice(tempPrice);

        if ( indexOfArray < arraySize ) //shifting array index while not exceeding array size
            indexOfArray++;
    }

    fileIn.close();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

和文本文件:

Author1
Book1
23.99
Author2
Book2
10.99
Autho3
Book3
14.56
Run Code Online (Sandbox Code Playgroud)

Bre*_*all 5

看起来你正试图在循环中写入bookList [3].每次都会循环三次填充数组递增indexOfArray.这将使indexOfArray保持在3 - 您写入的条件将允许indexOfAray增加到3.然后,如果您的数据文件中的"14.56"后面有换行符,您将再次循环并尝试传递空string to bookList [indexOfArray] .setAuthor()导致段错误,因为indexOfArray超过了数组的末尾.

我建议放弃硬编码数组并使用std :: vector代替.在每个循环的开始处,只需使用push_back()将新书添加到向量的末尾,然后使用back()来访问数组中的新元素.