【发布时间】:2016-07-18 07:18:40
【问题描述】:
我需要一些帮助来创建一个将 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
【问题讨论】:
-
如果我们知道 names.txt 文件的内容会有所帮助....
-
这是一个大约 4429 行的列表,每行以名称开头,后跟 11 列 int
-
名称中有空格吗?什么是分隔符?请编辑几行用于您的问题的实际文件。
-
那么这些都是空格,每行数据之间有一个空行?然后根据定义,名称不能有空格?
标签: c++ arrays data-structures struct c-strings