0

I'm aware that scanf() can be used when you know what data type the user will input. What if that information is unknown, and you would like to be able to handle any type? Is there an easy way to accomplish this?

i.e. assuming some class whichClass and function genericScan()

int main(int argc, const char * argv[]){

   whichClass *entry = [[whichClass alloc]init];

   genericScan(&entry);

   if(entry.isDouble())
      NSLog(@"You entered a double!");
   else if(entry.isFloat())
      NSLog(@"You entered a float!");
   else if(entry.isInteger())
      NSLog(@"You entered an integer!");
   else if (entry.isChar())
      NSLog(@"You entered a char!");
   else
      NSLog(@"Unknown data type!");

   return(0);
   }
2
  • Take a look at @encode() Commented Jul 14, 2013 at 4:01
  • @CodaFi - I think you've misread the question... Commented Jul 14, 2013 at 5:02

2 Answers 2

1

Yes, using NSScanner. In outline:

  • First obtain your input as an NSString in whatever way you wish.

  • Now create an NSScanner using +scannerWithString: or +localizedScannerWithString:.

  • Now call the various scanX: methods; e.g. scanInteger:, scanDouble:; in an appropriate order; e.g. look for floating point numbers before integers; until you get find a suitable interpretation of the string. Each of these methods returns a BOOL indicating whether it was successful in parsing a value.

Note you shouldn't try to distinguish different sized values of the same kind this way; parse them as the largest type of the kind (e.g. NSDecimalNumber (if you wish to support those) or double for floating point, long long for integers) and then use range checks if you wish to find a smaller type that can represent the value.

Sign up to request clarification or add additional context in comments.

Comments

0

I think that this would get you what you're aiming for

char *data = malloc(sizeof(char *) * 256);
fgets(data, 256, stdin);
NSString *dataString = [NSString stringWithCString:data];
NSInteger intValue = [dataString integerValue];
// double d = [dataString doubleValue];, etc.

That would get whatever data the user entered, and put it's corresponding values in an int, double, etc. If there is no integerValue, for example, it would return 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.