Reading from a text file into an array

Discussion in 'Mac Programming' started by jeremyn9, Jan 6, 2009.

  1. jeremyn9 macrumors newbie

    Joined:
    Jan 5, 2009
    #1
    Hi guys

    I want to read a list of figures(double) into an array. as the list of figures is fairly long and i have it in excel form actually, i wan wondering if it is possible to read a column of such figures into an array. Can any1 point me in the rite direction?

    I read thru Kochan's book and believe that he does not give such an example(according to my understanding, pls correct me if im wrong since i see tt many here have read his book)

    Many thanks for reading. Im using cygwin btw.
    jeremy
     
  2. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    To read Excel data you'd need an external library for that. If it's plain text you could start with NSString's stringWithContentsOfFile and parse through that.
     
  3. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #3
    To expand on Kainjow's idea, you could then use NSString's componentsSeparatedByString: or componentsSeparatedByCharactersInSet:
    to tokenize the NSString with your file's contents by, for example, newlines. You could then iterate over the NSArray returned and use NSString's doubleValue to get the primitive double type representation of the contents of each NSString. You said you wanted an array, and double is not an NSObject, so you could not store these directly in an NSArray. You could box the result of doubleValue in an NSNumber and store that, I suppose. It just depends on what you need to do with the array once you have it. If you wanted a C-style array of doubles, you'd need to resort to C-style dynamic memory management, declaring a double *, and assigning the result of a malloc to it like so:
    Code:
    NSArray *myStringArray = [myFileContentsString componentsSeparatedByString:@"\n"];
    double *myDoubleArray = (double *)malloc([myStringArray count]*sizeof(double));
    
    This assumes myFileContentsString has the contents of your file in it already. After this, you'd loop over the contents of myStringArray, using doubleValue and assigning each value to an element of myDoubleArray.

    -Lee
     

Share This Page