0

I am converting a string to signed integer via NSScanner:scanInteger, but it seems to be accepting values such as '123abc' as '123', instead of throwing a error on invalid input.

I can do my own custom validation, but would prefer to find an API which will do the conversion and fail on '123abc'.

By the way, 'abc123' does fail with scanInteger, which is good.

Locksleyu
  • 5,192
  • 8
  • 52
  • 77
  • What does it output, the integer '123'? If so, does it matter that it is ignoring the non-number characters? – Oliver May 29 '12 at 14:20
  • The problem is that I want to have strict validation of my input parameters for a command line tool. If I only allow 0-100 for values and the user puts in '100ABC', I want to tell them to get rid of the ABC and try again. Yes I could just let it slide but the user has some misunderstanding (or typo) that I think they should understand and correct. – Locksleyu May 29 '12 at 14:23

1 Answers1

0

I don't think that using a scanner is the way to do this -- you could, but there are easier ways. I would use the NSString method rangeOfCharactersFromSet: to check for non-digit characters.

NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSUInteger nonDigits = [enteredString rangeOfCharacterFromSet:notDigits].length;

If nonDigits is not zero, then the user has entered something other than a digit. If you want to allow decimal points then you would have to create your own set that contains everything other than digits and the decimal point.

rdelmar
  • 103,982
  • 12
  • 207
  • 218