File output as .csv objective C
Hello guys I'm writing a test file for a program. where all the possible numbers are tested and i want the result to be logged as a .csv file,so i can upload it into excel.
float calc (float i, float j , float p, float ex){
float nodalatio = (p/ex);
float ans = (0.68 *j + 1.22*nodalatio + 0.34*j -0.81);
return ans;
}
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
float stage , grade, pos, ex;
float resul;
for (int i=1;i<=3;i++){
stage = i;
for(int j=1;j<=3;j++){
grade = j;
for(int p=1;开发者_JAVA技巧p<=60;p++){
pos = p;
for(int e=1;e<=60;e++){
ex=e;
resul = calc(stage, grade,pos,ex);
NSLog(@"stage is %f grade is %f,pos is %f ex is %f the result is %f",stage,grade,pos,ex,resul);
}
}
}
}
[pool drain];
return 0;
}
the above is the test code and i can't seem to figure how to output this in to a .csv file. does the code in the loop or after the loop. this is what i had but this did nothing !
NSString *file_path = @"test.csv";
NSString *test_1 = [NSString stringwithformat@"%f",resu];
[test_1 writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil];
thank you
Try this:
float calc(float, float, float, float);
float calc (float i, float j , float p, float ex)
{
float nodalratio = (p / ex);
float ans = (0.68 * j + 1.22 * nodalratio + 0.34 * j - 0.81);
return ans;
}
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
float stage , grade, pos, ex;
float resul;
[[NSFileManager defaultManager] createFileAtPath: @"test.csv" contents: [@"" dataUsingEncoding: NSUnicodeStringEncoding] attributes: nil];
NSFileHandle *file = [NSFileHandle fileHandleForWritingAtPath: @"test.csv"];
[file seekToEndOfFile];
for (int i = 1; i <= 3; i++)
{
stage = i;
for(int j = 1; j <= 3; j++)
{
grade = j;
for(int p = 1; p <= 60; p++)
{
pos = p;
for(int e = 1; e <= 60; e++)
{
ex = e;
resul = calc(stage, grade, pos, ex);
NSString *str = [NSString stringWithFormat: @"%f, %f, %f, %f, %f\n", stage, grade, pos, ex, resul];
[file writeData: [str dataUsingEncoding: NSUTF16LittleEndianStringEncoding]];
}
}
}
}
[file closeFile];
[pool drain];
return 0;
}
That works for me. It will contain a proper BOM and write each string in UTF-16 (Unicode). Using other encodings, like NSUTF16StringEncoding, will write a BOM for each line, which is not really what you want.
FWIW, are you sure it is not 0.68 * j
and 0.34 * i
or vice versa?
Don't reinvent the wheel:
http://github.com/davedelong/CHCSVParser
My CSV parser class also includes a CSV writer for creating CSV files.
精彩评论