【问题标题】:Reading data from file into array of structs C++将文件中的数据读入结构数组 C++
【发布时间】:2009-08-05 12:31:41
【问题描述】:

我有一个示例 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

【问题讨论】:

  • 你的问题是?顺便说一句,您的代码非常错误。
  • 在很长一段时间后从 C 迁移到 C++ :)

标签: c++ file struct


【解决方案1】:
istream& operator >> (istream& is, PersonId &p)
{
    is >> p.fId;
    return is;
}

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

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

而不是

indata >> is;

indata >> p[i];

【讨论】:

  • 另外,在 while 循环之前将 i 初始化为零,并在 cout 之后移动 i++。
  • struct PersonId { int fId; };结构 PersonData { public: typedef PersonData* Ptr;个人数据();人名 fId; istream& 读取(std::istream&); }; istream& PersonData::read(std::istream& is) { is >> fId;回报是; } istream& operator >> (istream& is, PersonData &p) { // is >> p.fId;返回 p.read(is); indata >>p[i] 在这种情况下如何工作??
【解决方案2】:

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

【讨论】:

  • 我避免使用 getline() bcos 以后我会在一行中有很多数字,这将是相同结构的项目。
  • Getcha,但我更担心你使用 eof()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2013-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
相关资源
最近更新 更多