gpt4 book ai didi

c++ - 从文件中读取数据到结构数组 C++

转载 作者:行者123 更新时间:2023-11-28 04:00:08 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

代替

indata >> is;

indata >> p[i];

关于c++ - 从文件中读取数据到结构数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1232964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com