将数据从文件读取到结构体C ++的数组中 [英] Reading data from file into array of structs C++

查看:719
本文介绍了将数据从文件读取到结构体C ++的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例txt文件,并希望将该文件的内容读入结构数组。
我的persons.txt文件包含5个任意的每行一个。

I have a sample txt file and want to read the contents of the file into an array of structs. My persons.txt file contains 5 arbitrary nos one on each line.

7
6
4
3
2

我的程序如下所示:

#include <iostream>
#include <fstream>

using namespace std;

struct PersonId
{
    typedef PersonId* ptr;
    PersonId();
    int fId;
}; 

istream& operator >> (istream& is, PersonId &p)
{
    is >> p;
    // return is;
    // return p.read(is);
}

// istream& PersonData::read(std::istream& is) 
// {
//  is >> fId;
//  return is;
// }


int main ()
{
    ifstream indata;
    int i, is;
    indata.open("persons.txt", ios::in); // opens the file

    if(!indata) 
    { // file couldn't be opened
          cout << "Error: file could not be opened" << endl;
          exit(1);
    }

    int n = 5;
    PersonId* p;
    p = (PersonId*) malloc (n * sizeof(PersonId));

    while ( !indata.eof() )
    { // keep reading until end-of-file
    	// p[i].read();
    	indata >> is;
    	i++;
    	cout << "The next number is "<< is << endl;
            cout << "PersonId [" << i << "] is " << p[i].fId << endl;
        // indata >> is; // sets EOF flag if no value found
    }
    return 0;
}

我的输出如下所示:

test6.cpp: In function ‘std::istream& operator>>(std::istream&, PersonId&)’:
test6.cpp:27: warning: control reaches end of non-void function
The next number is 7
PersonId [1] is 0
The next number is 6
PersonId [2] is 0
The next number is 4
PersonId [3] is 0
The next number is 3
PersonId [4] is 0
The next number is 2
PersonId [5] is 0


推荐答案

istream& operator >> (istream& is, PersonId &p)
{
    is >> p.fId;
    return is;
}

(读取p的成员fId,而不是整个结构)

(Reading the member fId of p, not the entire structure)

而在main中,读取结构,而不是值:

And the the while in main, read the structure, not a value:

而不是

indata >> is;

put

indata >> p[i];

这篇关于将数据从文件读取到结构体C ++的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆