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

标签 c++ arrays file initialization

当我尝试在 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;
}

和文本文件:

Author1
Book1
23.99
Author2
Book2
10.99
Autho3
Book3
14.56

最佳答案

看起来您正在尝试在循环中写入 bookList[3]。您将循环三次填充数组,每次递增 indexOfArray。这将使 indexOfArray 保持在 3——您编写的条件将允许 indexOfAray 递增到 3。然后,如果您在数据文件中的“14.56”之后有一个换行符,您将再循环一次并尝试传递一个空的string 到 bookList[indexOfArray].setAuthor() 导致段错误,因为 indexOfArray 超出了数组的末尾。

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

关于c++ - 使用文本文件中的数据初始化对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1703941/

相关文章:

c++ - 对相邻元素使用新的非数组放置是否会创建数组?

c++ - C++ 类方法的 LD_PRELOAD

c++ - 在 C++ 中初始化 vector 的 vector

java - 阻止文件截断 Java?

c++ - 如何使用标准跨度进行边界检查?

javascript - 通过 ID 比较 2 个不同的数组并计算差异

ios - NSArray filterArrayUsingPredicate 从不返回/阻塞执行

c++ - 如何从一个文件中读取数据并将其导入到另一个文件中?

c++ - 为什么代码打印所有第一个索引?

iPhone 文件扩展名应用关联