从文件读入结构

Read in from file into structure

本文关键字:结构 从文件读      更新时间:2023-10-16

我想使用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));
}

如果您的namebrand包含空格,则以上内容将不起作用,您需要编写一种格式,以便知道何时相应地停止abd读取,例如使用std::getline()

您还可以考虑使用合适的运算符包装逻辑以读取或写入对象。

istream& getline (istream&  is, string& str, char delim);

看看第三个参数,您可以使用std::getline来解析您的行。但这绝对不是序列化对象的最佳方式。您应该使用字节流,而不是使用文本文件。