【发布时间】:2013-04-11 17:29:42
【问题描述】:
这是我第一次尝试用 mac 编程。学习曲线陡峭。我有一个 .csv 文件,其中包含几列 ascii 数据组织的空白字段、用户名、姓名(格式为“姓氏、名字中间名”)、作业 1 级(整数)、作业 2 级(整数).... 作业n 等级(整数),平均等级(下降一个等级),部分编号(整数)。 代替等级,它们可能是作业栏中的文本条目:I 代表生病,X 代表豁免等。 我需要按部分计算每个作业的平均成绩。 IE。第 9999 节学生的平均成绩为 __。我已经查看了各种解析方案,但在我对目标 c 的理解中,这些方案太复杂了,无法知道如何使用它们,更不用说它们是如何工作的了。所以我要链接一些更具体、更不通用的东西。
我已经编写了一些代码来将文件读入一个长字符串。 我已经编写了将字符串分解为代码行数组的代码(学生 n 的成绩) 我对如何将行数组分解为二维项目行数组感到困惑。 完成后,我想通过查看单个作业的每一列成绩来计算每个作业的部分平均值。如果该行的学生在我正在计算的部分中,我想对数字成绩求和,跳过任何 S 或 X 条目并除以数字条目的数量以获得该作业的平均值。
最终我会输出一个 csv 文件,其中包含部分编号、每个作业的平均成绩、每个作业的累积成绩。
那么对于我的第一个问题,如何将数组分解为项目以及如何使用数字索引访问各个项目?任何建设性的指导都将被非常亲切地接受。
这是我到目前为止所做的:
// main.m
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool
{
// insert code here...
// beginning of sample code ************************************
// content is a pointer to a string containing all the data from the file
// contentarray is a pointer to an array where each index is a line from the file (separated by \n
// itemarray is a pointer to an array where the primary index - row is the nth line of the file and column is the nth item in the line.
NSInteger itemcount, rowcount;
NSString *pathwithgradefile = @"/some_path/sampledata.csv";
// NSError *error = nil;
NSString *content = [NSString stringWithContentsOfFile:pathwithgradefile encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",content);
Make array of lines from the file - This part works.
NSArray *contentArray = [content componentsSeparatedByString:@"\n"]; // csv file line ends with newline
// output check of contentarray.
NSLog(@" \nlist contentArray line by line\n");
rowcount=0;
for (NSString *item in contentArray) {
// display item
NSLog(@"\n\r");
NSLog(@"row count: %lid Content: %@",rowcount, [contentArray objectAtIndex:rowcount]);
rowcount++; // this section works
}
// parse into 2d array with rows and items in each row
// this section is bogus - I am really clueless on how to proceed.
itemcount=0;
for (NSString *item in contentArray) {
NSArray *itemArray = [item componentsSeparatedByString:@","];
// log first item
NSLog(@"\n\r");
NSLog(@"item count: %lid Content: %@",itemcount, [itemArray objectAtIndex:rowcount]);
itemcount++;
}
}
return 0;
}
【问题讨论】:
-
简而言之,您有一个 contentArray 并且您想制作 2D 数组?
标签: objective-c macos cocoa parsing csv