NSScanner never reaches "isAtEnd" or don't scann full string

1.1k views Asked by At

I've got an issue making scanner working for this particular string.

here comes the code :

tempString = @"30.15 in. Hg (1021 hPa)";
scanner = [NSScanner scannerWithString:tempString]; //setting the scanning location,
[scanner setCharactersToBeSkipped:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789.,-+ "]invertedSet]];
value = 0;
_i = 0;
while([scanner isAtEnd] == NO)
{
    [scanner scanFloat:&value];
    if(_i == 1)
    {
        pressure = value;
    }
    _i++;
}
NSLog(@"pressure = %f hpa",pressure);

this infinity loop...

if I change the string with : tempString = @"30.15 in 8.8 Hg (1021 hPa)";

then it works fine

also if I change with : tempString = @"30.15 in Hg (1021 hPa)";

it also works fine.

the issue comes from the "." (dot)

any clean solution to make this work ?

thanks a lot.

2

There are 2 answers

0
kennytm On BEST ANSWER

You can check if -scanFloat: returns YES to check if a valid float is scanned. Skip the character if it returns NO.

while (![scanner isAtEnd]) {
    if ([scanner scanFloat:&value]) {
      if(_i == 1) {
        pressure = value;
      }
      _i++;
    } else {
      [scanner setScanLocation:[scanner scanLocation] + 1];
    }
}
2
Jakob Egger On
tempString = @"30.15 in. Hg (1021 hPa)";
scanner = [NSScanner scannerWithString:tempString];
[scanner scanUpToString:@"(" intoString:nil];
[scanner scanString:@"(" intoString:nil];
[scanner scanFloat:&value];