从c ++中的文本文件读取结构

时间:2017-04-29 19:37:37

标签: c++ file ifstream

stats.txt

ifstream reader("stats.txt",ios::in);
cout<<setw(3)<<"id"<<setw(20)<<"name"<<setw(10)<<"match1"<<setw(10)<<"match2"<<setw(10)<<"match3"<<setw(10)<<"match4"<<setw(10)<<"match5";

player p1;
for(int i=0;i<25;i++)
{
    reader>>p1.id;
    reader>>p1.name;
    reader>>p1.matches[0];
    reader>>p1.matches[1];
    reader>>p1.matches[2];
    reader>>p1.matches[3];
    reader>>p1.matches[4];
    cout<<endl;
    cout<<setw(3)<<p1.id<<setw(20)<<p1.name<<setw(10)<<p1.matches[0]<<setw(10)<<p1.matches[1]<<setw(10)<<p1.matches[2]<<setw(10)<<p1.matches[3]<<setw(10)<<p1.matches[4];
}

所以我有一个看起来像这样的文本文件,我想将这些内容读入我形成的结构并使用结构变量。现在我只是试图在控制台上显示它并且效果不佳。

2 个答案:

答案 0 :(得分:1)

对我来说,显而易见的方法是首先定义一个结构来保存你读取的每一行数据:

struct record { 
    static const int match_count = 5;
    int id;
    char name;
    int match[match_count];
};

然后我为这种类型定义提取和插入运算符:

std::istream &operator>>(std::istream &is, record &r) { 
    is >> r.id >> r.name;
    for (int i=0; i<r.match_count; i++)
        is >> r.match[i];
    return is;
}

std::ostream &operator<<(std::ostream &os, record const &r) { 
    os << std::setw(3) << r.id << std::setw(20) << r.name;
    for (int i=0; i<r.match_count; i++)
        os << std::setw(10) << r.match[i];
    return os;
}

最后,做真正的工作:

  1. 打开输入文件
  2. 忽略第一行(一切直到第一个新行)
  3. 将记录从流复制到cout
  4. 代码可能如下所示:

    int main() { 
        std::ifstream in("stats.txt"); // open the file
    
        in.ignore(1024, '\n');         // ignore the first line
    
        std::istream_iterator<record> b(in), e;
        std::copy(b, e,                // copy records from file to cout
            std::ostream_iterator<record>(std::cout, "\n"));
    }
    

答案 1 :(得分:0)

为什么你的数据文件中还有第一行文本,因为你的程序不需要它?程序使用的数据文件应该只包含用于程序的数据......没有别的。

如果您的程序需要该文本行,则将其放入单独的文本文件中并根据需要进行访问。

Dr t

相关问题