从具有任意空间量的文件中获取数据集

grabbing data sets from a file with an arbitrary amount of spaces

本文关键字:文件 获取 数据集 任意 空间      更新时间:2023-10-16

**请不要直接回答或代码示例,这是我需要学习的家庭作业。我正在寻求有关我需要开发的算法的帮助。

我似乎在为课堂上的一部分工作提出解决方案时出现了逻辑错误,该程序涉及多个文件,但这里是唯一相关的部分:

我有一个文件PlayerStats,它保存了中篮球运动员的统计数据

  • 篮板
  • 协助
  • 制服#

我的初始反应是创建一个while循环,并将这些值读取到一个保存这些值的临时结构中,然后创建一个合并函数,将临时结构的值与记录的初始数组合并,够简单吗?

struct Baller
{
//other information on baller
int rebounds;
int assists;
int uniform;
int points;
void merge(Baller tmp); //merge the data with the array of records
}
//in my read function..
Baller tmp; 
int j = 0;
inFile << tmp.uniform << tmp.assists << tmp.points << tmp.rebounds
while(inFile){
ArrayRecords[j].merge(tmp);
j++;
//read in from infile again
}

捕获:文件的标识符之间可以有任意数量的空格,并且信息可以按任何顺序排列(不包括统一编号,始终是第一个)。例如

PlayerStats可能是

11 p3 a12 r5 //uniform 11, 3 points 12 assists 5 rebounds
//other info

11 p    3 r  5  a      12 //same exact values

我的想法


似乎想不出一种算法来以正确的顺序从文件中获取这些值,我想的是:

inFile << tmp.uniform; //uniform is ALWAYS first
getline(inFile,str);  //get the remaining line
int i = 0;
while(str[i] == " ") //keep going until i find something that isnt space
i++;
if(str[i] == 'p')  //heres where i get stuck, how do i find that number now?
else if(str[i] == 'a')
eles if(str[i] = 'r'

如果只检查一个字母,可以使用switch语句而不是if / else语句,这样会更容易阅读。

你知道这个数字从哪里开始,(提示:str[i+1]),所以根据你的str[]是什么类型,如果是char数组,你可以使用atoi,如果是std::string,你可以用std::stringstream

我很想给你一些代码,但你也不这么说。如果你确实想要一些,请告诉我,我会用一些代码编辑答案。

与其使用"merge"函数,不如尝试使用std::vector,这样您就可以只push_back您的结构,而不用执行任何"merge(合并)"操作。此外,您的merge函数基本上是一个复制赋值运算符,默认情况下由编译器创建(您不需要创建"merge"函数),您只需要使用=来跨复制数据。如果你想在"merge"函数中做一些特殊的事情,那么你应该重载复制赋值运算符,而不是"merge(合并)"函数。简单。

这样做:

int readNumber () {
while isdigit (nextchar) -> collect in numberstring or directly build number
return that number;
}
lineEater () {
Read line
skip over spaces
uniform=readNumber ();
haveNum=false;
haveWhat=false;
Loop until eol {
skip over spaces
if (isdigit)
number=readNumber ();
skip over spaces
haveNum=true;
else 
char=nextChar;
haveWhat=true;
if (haveChar and haveNum) {
switch (char) {
case 'p' : points=number; break;
...
}
haveNum=false;
haveWhat=false;
}
}

或者,如果您比较模糊,可以为您的输入编写一个语法,并使用lex/yacc。