从文件c++中读取,然后创建对象
read from file c++ then create object
我需要一些帮助来读取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的序列化库。这对于从文件中写入和读取对象非常有效。不利的一面是它没有那么可读。
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- 创建对象并防止被破坏
- C++ std::vector 创建对象然后添加对象与在向量中创建对象之间的区别?
- 从文件c++中读取,然后创建对象
- 创建对象数组然后有效删除它们的更好方法