在使用数据结构从文件中读取数据时遇到麻烦

Trouble reading in data from a file using data structures

本文关键字:数据 读取 遇到 麻烦 文件 数据结构      更新时间:2023-10-16

我有一个包含汽车租赁信息和公司信息的程序。我正试图读取它,并有它显示在终端上。然而,我只让一家公司打印清晰,而其他公司只打印垃圾。我也想用5辆车的库存来存储代理,但不知道如何在没有读取所有信息的情况下存储它们。我也只能使用c风格的字符串。

这是我正在阅读的文件:

Hertz 93619
2014 Toyota Tacoma 115.12 1
2012 Honda CRV 85.10 0
2015 Ford Fusion 90.89 0
2013 GMC Yukon 110.43 0
2009 Dodge Neon 45.25 1
Alamo 89502
2011 Toyota Rav4 65.02 1
2012 Mazda CX5 86.75 1
2016 Subaru Outback 71.27 0
2015 Ford F150 112.83 1
2010 Toyota Corolla 50.36 1
Budget 93035
2008 Ford Fiesta 42.48 0
2009 Dodge Charger 55.36 1
2012 Chevy Volt 89.03 0
2007 Subaru Legacy 59.19 0
2010 Nissan Maxima 51.68 1

需要帮助的代码段:

#include <iostream>
#include <fstream>
using namespace std;
struct car
{
        char agency[10];
        int zip;
        int year;
        char make[10];
        char model[10];
        float price;
        int available;
} ;
struct agency
{
    char company[10];
    int zip;
    int inventory[5];
};
void menu();

// Main Function
int main ()
{
    // declare variables
    const int carAmount = 15;
    int agencyAmount = 1;
    int choice;
    agency agencyLib[carAmount];
    car carLib[carAmount];
    char filename[10];
    ifstream carInData;
    bool menu1 = false;
    //prompt user for input file
    cout << " Enter file name: ";
    cin >> filename;
    // Start loop menu
    while(menu1 = true)
    {
        menu();
        carInData.open(filename);
        cin >> choice;
        if (carInData.is_open())
        {
            // read list of names into array
            for (int count = 0; count < agencyAmount; count++) 
            {
                carInData >> agencyLib[count].company >> agencyLib[count].zip;
                for (count = 0; count < carAmount; count++)
                {
                    carInData >> carLib[count].year >> carLib[count].make >> carLib[count].model >> carLib[count].price >> carLib[count].available;
                }
            }
        }
    switch (choice)
    {
        // Case 1 closes menu
        case 1:
            return 0;
            break;
        // Case 2 displays if car is available if 1, unavailable if 0
        case 2:
        // itterate through car array
            for(int count = 0; count < agencyAmount; count++)
            {
                cout << agencyLib[count].company << " " << agencyLib[count].zip << "n";
                for(int count = 0; count < carAmount; count++)
                {
                    // Displays if car is available or not 
                    /*      if (carLib[count].available == 1)
                    cout << " Available ";
                    else
                        cout << " Unavailable ";
                    */
                    // Display Cars
                    cout << carLib[count].year << " " << carLib[count].make << " " << carLib[count].model << " " << carLib[count].price << "  " << "n";
                }
            }
        }
    }
}

作为一般的初步评论,我认为即使是出于学习目的,这种练习也应该让您使用std::strings而不是c-strings和std::vector来保持越来越多的项目。

你的代码有什么问题?

第一个问题是您使用相同的计数器count来填充代理数组和汽车数组。这将很快导致计数器超出数组边界并破坏内存。

解决方案:使用2个不同的计数器重新设计你的循环结构。

下一个问题是,你没有确定一个机构的汽车列表的末尾。这使得读取多个代理是不现实的:您将遇到流读取失败,这将阻止您从数据中获取任何有用的内容。

解决方案:分析读取失败,以识别从汽车(第一个元素应该是数字)到新机构(第一个元素是字符串)。

另外,你可能有一些字符串比你的字符数组允许的长,导致进一步的内存损坏。

解决方案:使用iomanip()限制读取的字符数来固定最大宽度。强烈建议这样做,除非您选择std::string

最后一个问题:可变长度数组不是标准的c++特性,即使一些流行的编译器支持它。

解决方案:要么使用new/delete动态分配,要么在本练习中选择使用恒定的最大大小。

代码片段:

经过调整后,没有选择、菜单等,阅读内容看起来像:

const int carAmount = 30;    // !!!
const int agencyAmount = 10;  // !!!
agency agencyLib[carAmount];
car carLib[carAmount];
ifstream carInData ("test.dat");
int numCar = 0, numAgency = 0;        // !!! shows the real number of items available
int count1, count2;                   // 
cout << "Start reading" << endl;
for (numAgency = numCar = 0; carInData && numAgency < agencyAmount; numAgency++) {
    if (!(carInData >> setw(sizeof(agencyLib[numAgency].company)) >> agencyLib[numAgency].company >> agencyLib[numAgency].zip))
        break;  // if nothing left, exit loop immediately
    for (; numCar < carAmount; numCar++) {
        carInData >> carLib[numCar].year >> setw(sizeof(carLib[numCar].make )) >>carLib[numCar].make 
                                         >> setw(sizeof(carLib[numCar].model))>>carLib[numCar].model 
                                         >> carLib[numCar].price >> carLib[numCar].available;
        if (carInData.fail()) { // here we expect a year, but get an agency string 
            carInData.clear(); 
            break;
        }
        strcpy(carLib[numCar].agency, agencyLib[numAgency].company);
        carLib[numCar].zip = agencyLib[numAgency].zip;
    }
}

和随后的显示:

cout << "Display agencies: " << endl; 
for (count1 = 0; count1 < numAgency; count1++) {
    cout << agencyLib[count1].company << " " << agencyLib[count1].zip << "n";
}
cout << "Cars: " << endl;
for (count2 = 0; count2 < numCar; count2++) {
    cout << carLib[count2].agency << " " << carLib[count2].zip << ": "; 
    cout << carLib[count2].year << " " << carLib[count2].make << " " << carLib[count2].model << " " << carLib[count2].price << "  " << "n";
}

注意,代理和汽车之间没有链接(除了公共字段),所以显示只显示两个不同的列表。