将数据从文件读入结构C ++数组

时间:2009-08-05 12:31:41

标签: c++ file struct

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

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

2 个答案:

答案 0 :(得分:2)

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

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

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

而不是

indata >> is;

indata >> p[i];

答案 1 :(得分:0)

请参阅Neil Butterworth对ifstream object.eof() not working的回复,了解如何正确读取istream