从文件c++中读取,然后创建对象

read from file c++ then create object

本文关键字:然后 创建对象 读取 文件 c++      更新时间:2023-10-16

我需要一些帮助来读取visual c++中的文件。从"movie.dat",我需要阅读这个:

2015,Star Wars,DVD,120
1987,Star wars,DVD,110
2010,Inception,DVD,100

类似的东西

使用逗号(,)分隔符并添加到字段中,如:

store.add(year,name,media,length)

在java中,我会这样做:

public static void readFromFile(String filename,Store store){
        try {
            Scanner ps = new Scanner(new BufferedInputStream(new FileInputStream(filename)));
            while(ps.hasNextLine()){
                String line = ps.nextLine();
                String field[] = line.split(",");
                store.add(Integer.parseInt(field[0]),field[1],field[2],Integer.parseInt([3]));
            }
            ps.close();
        } catch(Exception e){
            System.out.println(e.getMessage());
        }
    }

好吧,我首先定义一个结构(或类)来保存数据:

struct movie { 
    int year;
    std::string name;
    std::string media;
    int length;    
};

然后我定义一个提取器来从文件中读取其中的一个:

std::istream &operator>>(std::istream &is, movie &m) {
    std::string line;
    std::getline(is, line);
    std::istringstream buffer(line);
    char ignore;
    buffer >> m.year >> ignore;
    std::getline(buffer, m.name, ',');
    std::getline(buffer, m.media, ',');
    buffer >> m.length;
    return is;
}

然后我会从一个文件中读取一个向量(例如):

std::vector<movie> movies {
    std::istream_iterator<movie>(infile),
    std::istream_iterator<movie>() };

你应该用基本的get set函数编写你的电影类,并将信息存储在电影类对象的向量中

void readMovieDataFromFile(vector<movie> &movies) {
fstream  inputfile;
std::string line;
inputfile.open("C:\movie.dat", ios::out | ios::in );   
std::string token;
while (std::getline(inputfile, line)) {
    std::istringstream iss(line);
    while (std::getline(iss, token, ','))
    {
        movies[i].setYear(atoi(token.c_str()));
        std::getline(iss, token, ',');
        movies[i].setName(token);
        std::getline(iss, token, ',');
        movies[i].setMedia(token);
        std::getline(iss, token, ',');
        movies[i].setLength(atoi(token.c_str()));
    }
    i++;
}
inputfile.close();
}
void readMovieDataFromFile() {
fstream  inputfile;
std::string line;
inputfile.open("filmy.dat", ios::in);

while (std::getline(inputfile, line)) {
    std::istringstream iss(line);
    std::string token;
    while (std::getline(iss, token, ','))
    {
        int a = atoi(token.c_str());
        std::getline(iss, token, ',');
        char *y = new char[token.length() + 1];
        std::strcpy(y, token.c_str());

        std::getline(iss, token, ',');
        char *c = new char[token.length() + 1];
        std::strcpy(c, token.c_str());

        std::getline(iss, token, ',');
        int b = atoi(token.c_str());
        store.add(a, y, c, b);
    }
}

谢谢你为我所做的一切!:)

使用类似boost::serialization的序列化库。这对于从文件中写入和读取对象非常有效。不利的一面是它没有那么可读。