首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从文件读入结构

从文件读入结构
EN

Stack Overflow用户
提问于 2013-12-07 04:52:45
回答 3查看 1K关注 0票数 0

我想使用fstream将txt文件读入到结构中。我以如下所示的方式将数据保存到文件中:为了读取数据,我尝试了一些使用getline或tabsin<的方法

代码语言:javascript
复制
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();

//输入失败的部分:(

代码语言:javascript
复制
    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();
EN

回答 3

Stack Overflow用户

发布于 2013-12-07 05:22:30

您通常希望重载类/结构的operator>>operator<<,并将读/写代码放在那里:

代码语言:javascript
复制
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;
    }
};

然后,您可以读入一个对象文件,如:

代码语言:javascript
复制
std::ifstream tabsin("tab.txt");
std::vector<tab> tabs{std::istream_iterator<tab>(tabsin), 
                      std::istream_iterator<tab>()};

....and写出如下对象:

代码语言:javascript
复制
for (auto const &t : tabs) 
    tabsout << t << "\n";

请注意(与任何理智的C++程序员一样),我使用了vector而不是数组,以便(尤其是)允许存储任意数量的项,并自动跟踪实际存储了多少项。

票数 3
EN

Stack Overflow用户

发布于 2013-12-07 05:27:29

对于初学者来说,不要使用 .eof()来控制你的循环:它不工作。取而代之的是,在读取以下内容后使用流的状态:

代码语言:javascript
复制
int type;
std::string name, brand;
while (in >> type >> name >> brand) {
    tabs.push_back(tab(type, name, brand));
}

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

您还可以考虑使用适当的操作符来包装逻辑以读取或写入对象。

票数 1
EN

Stack Overflow用户

发布于 2013-12-07 05:16:56

代码语言:javascript
复制
istream& getline (istream&  is, string& str, char delim);

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20433370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档