简体   繁体   中英

Reading data from file into array of structs C++

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

My program looks like this:

#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;
}

My output looks like this:

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;
}

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

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

instead of

indata >> is;

put

indata >> p[i];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM