简体   繁体   English

如何从文件中读取数据到一维结构数组中

[英]How to read data from a file into a 1-D array of structures

I'm working on my c++ program assignment and I can't wrap my head around how to read data in from a file into a 1-d array of structures. 我正在从事c ++程序的分配工作,我无法解决如何从文件中读取数据到一维结构数组中的问题。 My data file looks like this: 我的数据文件如下所示:

01 Jimmy Johnson 01吉米·约翰逊(Jimmy Johnson)
190 60 190 60

02 Gerald Hill 02杰拉尔德·希尔
180 56 180 56

The first number being their id, the next to words being their first and last names, and the next line is their height and weight. 第一个数字是其ID,第二个字是其身高和体重。 My teacher wants me to read this data into an array "Astronaut". 我的老师要我将这些数据读入数组“宇航员”。 And THEN somehow put the correct info into "NAME" and "BODYSTATS", using a 1-D array of structures, so I can correctly print the information later. 然后,使用一维结构数组以某种方式将正确的信息放入“名称”和“ BODYSTATS”中,以便以后可以正确打印该信息。 I've only gotten as far as reading data into a single array and printing it. 我只是将数据读入单个数组并进行打印。 How in the heck do I assign certain words in the array to certain (structs?) and be able to print them later? 我该如何在数组中将某些单词分配给某些(结构?)并在以后打印出来?

#include<string>
#include<fstream>
using namespace std;

struct ob
{
  string name;
  string id;
  int height;
  int weight;
};

int main()
{
  ob p[100];
  string emptyline;
  int count=-1;
  ifstream input("data.txt");
  while (input>>p[++count].id)
  {
     getline(input, p[count].name);
     p[count].name = p[count].name.substr(1);
     input>>p[count].height>>p[count].weight;
     getline(input, emptyline); // \n after weight
     getline(input, emptyline); // empty line
  }
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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