将文本文件存储到结构数组中

Storing a text file into an array of structures

本文关键字:结构 数组 存储 文本 文件      更新时间:2023-10-16

我需要一些帮助来创建一个函数,该函数将把txt文件中的数据读取到结构数组中。我在尝试将数据存储在数组列表中时遇到问题。应该调用函数loadNames来读取整个names.txt文件,并将每行的数据存储到Name类型的结构中。主函数应该将一个Name结构数组传递给loadNames,这样它就可以简单地将一行的数据读取到该数组第一个元素的结构中,然后将第二行的数据读入第二个元素中,等等。这应该针对names.txt文件的所有4429行执行。一旦loadNames完成并返回到main,在执行应用程序期间,就不能再读取文件names.txt。

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
const int SIZE=4429;
const int NAME_LEN=21;
const int NUM_RANKS=11;
//Structure used to store the data contained on one line of the file.
//name is an array of strings.
//rank is an array of int storing
struct Name{
    char name[21];
    int rank[11];
 };
void loadNames(Name []);
int main(){
    Name list[SIZE];
    char choice;
    loadNames(list);
    return 0;
}
//The function that has been kicking my ass I tried using a loop
//to populate the array but I'm unable to separate the strings and the       numbers
void loadNames( Name list[]){
    ifstream nameList;
    int count=0;
    char line[4430];
    int ch;
    nameList.open("names.txt");
    while((ch=nameList.peek())!=EOF){
        nameList.getline(line,SIZE);  // I was trying a [for] loop but I am        
                                      // not sure if it should replace the [while] loop. 
    };
   nameList.close();
 }

txt文件如下(它更长,但采用相同的格式

A 83 140 228 286 426 612 486 577 836 0 0
Aaliyah 0 0 0 0 0 0 0 0 0 380 215
Aaron 193 208 218 274 279 232 132 36 32 31 41
Abagail 0 0 0 0 0 0 0 0 0 0 958

所以我可以将文件中的数据存储到数组中,但现在我很难将数据分离为名称和数字

  void loadNames( Name list[]){
  int count=0;
  int ch;
  char line[SIZE];
  int lineNumber[SIZE];
ifstream nameList;
nameList.open("names.txt");
do{
        {
            nameList.getline(line,SIZE);
            strcpy (list[count].name, line);
            }
        count++;
}while((ch=nameList.peek())!=EOF);
nameList.close();