Sscanf Equivalent in Objective-C

3d, cocoa, objective-c

Solution

The NSScanner class can parse numbers in strings, although it can't be used as a drop-in replacement for sscanf.

Edit: here's one way to use it. You can also put the `/` into the list of characters to be skipped.

float temp[6];
NSString *objContent = @"f 1.43//2.43 1.11//2.33 3.14//0.009";
NSScanner *objScanner = [NSScanner scannerWithString:objContent];

// Skip the first character.
[objScanner scanString:@"f " intoString:nil];

// Read the numbers.
NSInteger index=0;
BOOL parsed=YES;
while ((index<6)&&(parsed))
{
    parsed=[objScanner scanFloat:&temp[index]];
    // Skip the slashes.
    [objScanner scanString:@"//" intoString:nil];

    NSLog(@"Parsed %f", temp[index]);
    index++;
}

Problem

I'm currently writing a wavefront OBJ loader in Objective-C and I'm trying to figure out how to parse data from an NSString in a similar manner to the sscanf() function in C. OBJ files define faces in x,y,z triplets of vertices, texture coordinates, and normals such as: ``` f 1.43//2.43 1.11//2.33 3.14//0.009 ``` I'm not concerned about texture coordinates at the current moment. In C, an easy way to parse this line would be a statement such as: ``` sscanf(buf, "f %d//%d %d//%d %d//%d", &temp[0], &temp[1], &temp[2], &temp[3], &temp[4], &temp[5]); ``` Obviously, NSStrings can't be used in a sscanf() without first converting them to a C-style string, but I'm wondering if there's a more elegant way to performing this without doing such a conversion.

Original source