从具有任意空间量的文件中获取数据集
grabbing data sets from a file with an arbitrary amount of spaces
**请不要直接回答或代码示例,这是我需要学习的家庭作业。我正在寻求有关我需要开发的算法的帮助。
我似乎在为课堂上的一部分工作提出解决方案时出现了逻辑错误,该程序涉及多个文件,但这里是唯一相关的部分:
我有一个文件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。
- C++ - 忽略并从其他文件获取数据
- 为什么从文件获取图标时应用程序有时会崩溃?
- 如何在 c++ 窗口中将参数和返回的退出值传递到批处理文件/从批处理文件获取返回的退出值
- Qt .pro 文件获取 Qtkit 名称
- 提升属性树:如何使用xml文件获取子树的子级
- 从C 中的二进制文件获取整数值时
- 如何在Windows上绕过主机文件获取真实的IP地址
- 如何使用 CPP/C# 从 VHDX 文件获取文件(或文件系统)
- 从读取到对象指针数组的文件获取段错误
- 是否可以从IOS项目中的cpp文件获取文件路径
- 将数据从头文件获取到源文件中的非成员函数中
- 从两个不同的文件获取输入时,输入会发生变化
- 从文件 C++ 获取整数
- 通过在 C++ 中使用发布模式二进制文件获取崩溃原因
- C++ 将值从文件获取到数组中
- 使用HTTP上载文件.获取错误:-HttpSendReuest 12005
- 正在从外部文件获取输入
- 读/写同一个文件(获取gmon.out)
- 从二进制文件获取输入时发生访问冲突错误
- 从特定文件获取函数指针