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