1

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.

Vassily
  • 899
  • 2
  • 8
  • 19

2 Answers2

2

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];
    }
}
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
0
tempString = @"30.15 in. Hg (1021 hPa)";
scanner = [NSScanner scannerWithString:tempString];
[scanner scanUpToString:@"(" intoString:nil];
[scanner scanString:@"(" intoString:nil];
[scanner scanFloat:&value];
Jakob Egger
  • 11,981
  • 4
  • 38
  • 48
  • thanks, this is indeed a good way to get round the issue. Also I'll be glad to understand the way it works : why does the dot "." make the scanner stops or why the scanner never reachs the end in the while loop. – Vassily Feb 07 '11 at 12:18
  • 1
    When you call `-scanFloat:`, the scanner checks if there is a decimal number at the current position. If there is, it puts this number into the passed argument, moves the current position after the number, and returns YES. If there is not a valid number, it returns NO and doesn't change the position. In your original loop you keep trying to scan the dot, and it always fails, because a dot is not a valid number. You should really look at the [NSScanner reference](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html). – Jakob Egger Feb 07 '11 at 12:30