从文件读入结构
Read in from file into structure
我想使用fstream从txt文件读入结构。我以如下所示的方式将数据保存到文件中:为了阅读数据,我用getlines或tabsin<
struct tab{
int type,use;
string name, brand;
};
tab tabs[500];
ofstream tabsout;
tabsout.open("tab.txt", ios::out);
for (int i = 0; i < 500; i++){
if (tabs[i].use==1){
tabsout << tabs[i].type << " " << tabs[i].name << " " << tabs[i].brand << "n";
}
}
tabsout.close();
//使我失败的输入部分:(
int i=0;
ifstream tabsin;
tabsin.open("tab.txt", ios::in);
if (tabsin.is_open()){
while(tabsin.eof() == false)
{
tabsin >> tabs[i].type>>tabs[i].name>>tabs[i].brand;
i++
}
tabsin.close();
您通常需要为类/结构重载operator>>
和operator<<
,并将读/写代码放在那里:
struct tab{
int type,use;
string name, brand;
friend std::istream &operator>>(std::istream &is, tab &t) {
return is >> t.type >> t.name >> t.brand;
}
friend std::ostream &operator<<(std::ostream &os, tab const &t) {
return os << t.type << " " << t.name << " " << t.brand;
}
};
然后你可以读取一个对象文件,比如:
std::ifstream tabsin("tab.txt");
std::vector<tab> tabs{std::istream_iterator<tab>(tabsin),
std::istream_iterator<tab>()};
并写出如下对象:
for (auto const &t : tabs)
tabsout << t << "n";
请注意(像任何理智的C++程序员一样)我使用了vector
而不是数组,以允许存储任意数量的项,并自动跟踪实际存储的项的数量。
对于初学者,不要使用.eof()
来控制循环:它不起作用。相反,在读取后使用流的状态:
int type;
std::string name, brand;
while (in >> type >> name >> brand) {
tabs.push_back(tab(type, name, brand));
}
如果您的name
或brand
包含空格,则以上内容将不起作用,您需要编写一种格式,以便知道何时相应地停止abd读取,例如使用std::getline()
。
您还可以考虑使用合适的运算符包装逻辑以读取或写入对象。
istream& getline (istream& is, string& str, char delim);
看看第三个参数,您可以使用std::getline来解析您的行。但这绝对不是序列化对象的最佳方式。您应该使用字节流,而不是使用文本文件。
相关文章:
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 将文件读入数据结构
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- (C++) 使用诅咒打印从文件中读入的新行
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- C++ 它没有从文件读回动态结构
- 将结构从文件写入/读取到 std::vector<>
- 从文件读入.多个分隔符?C++
- 从文件读入结构
- 使用字符串函数将数据从文件读入结构
- 函数从文件读入向量c++
- 从文件读到另一点c++
- 在使用数据结构从文件中读取数据时遇到麻烦
- 如何从文件读入双链表
- 从文件读入到数组
- 从文件读入矢量
- 将数字从文件读入数组
- 将数据从文件读入结构体,对数据进行排序并写入文件