将文本文件存储到结构数组中
Storing a text file into an array of structures
我需要一些帮助来创建一个函数,该函数将把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();
相关文章:
- C++将文本文件中的数据读取到结构数组中
- JSON转换为nlohmann JSON-lib中的结构数组
- 需要帮助将结构数组传递给函数
- 在 64 位边界上对齐C++结构数组?
- 带有枚举方向/类型的气泡排序结构数组
- 在C++中访问结构数组中的数据
- 从指向结构数组的指针中提取元素
- 如何制作一个地图,其中的值是C++中的结构数组
- 如何在函数中显示结构数组
- 包含作为成员C++函数的结构数组
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- std::transform 将一个结构数组复制到另一个结构数组
- 将非托管结构数组封送到托管数组
- 显示结构数组
- 结构数组中所有类似字段的总和
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 在 glsl opengl 中将嵌套结构数组作为统一传递
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何将字符串字符与结构数组进行比较?
- C++结构数组