如何正确地从txt文件读取到结构

时间:2016-11-27 00:47:22

标签: c++ struct fstream

我遇到的问题是以常规可读的方式保存它。所有输出的都是垃圾非字符数据。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

struct inventory {

int id;
int year;
string model;
string trim;
string color;
int engine;

};

int main() {

fstream inFile("inventory.txt", ios::in | ios::binary);
fstream accord("accord6.txt", ios::out | ios::binary);

int id;
int year;
string model;
string trim;
string color;
int engine;
int total = 0;
inventory honda[10], *temp = nullptr;

//copy items into the honda struc array
for (int count = 0; count < 10; count++) {

    inFile >> id >> year >> model >> trim >> color >> engine;

    honda[count].id = id;
    honda[count].year = year;
    honda[count].model = model;
    honda[count].trim = trim;
    honda[count].color = color;
    honda[count].engine = engine;
};

//dynamically allocate a new struc
for (int count = 0; count < 10; count++) {

    if (honda[count].model == "Accord") {
        total += 1;


    }
}
    temp = new inventory[total];
//program is designed to copy all accord details into another text file
    for (int count1 = 0; count1 < total; count1++) {

        for (int count = 0; count < 10; count++) {

            if (honda[count].model == "Accord")
            {
                temp[count1].id = honda[count].id;
                temp[count1].year = honda[count].year;
                temp[count1].model = honda[count].model;
                temp[count1].trim = honda[count].trim;
                temp[count1].color = honda[count].color;
                temp[count1].engine = honda[count].engine;
            }

        }
    }

    //just making sure everything copied correctly
    for (int count1 = 0; count1 < total; count1++) {

        cout << temp[count1].id << endl;
        cout << temp[count1].year << endl;
        cout << temp[count1].model << endl;
        cout << temp[count1].trim << endl;
        cout << temp[count1].color << endl;
        cout << temp[count1].engine << endl;
    }
//this is the problem here when creating the text file. when i open it, its nothing but garbage text. any ideas?
    accord.write(reinterpret_cast<char *>(&temp), sizeof(inventory));


}

这是我从“inventory.txt”中读取的文件:

1001 2014 Civic LX Red 4

1002 2014 Accord LX Blue 4

1005 2014 Accord EX Gold 6

1006 2014 Civic EX Black 4

1007 2014 Civic LX White 4

1010 2015 Accord EX White 6

1011 2015 Accord LX Black 4

1013 2015 Civic EX Red 4

1014 2015 Civic LX Beige 4

1015 2015 Accord EX Beige 6

0 个答案:

没有答案
相关问题