Thursday, December 11, 2014

Cocos2D-X: Convert String to Integer and Testing For Numeric Value

These can be done quite simply by converting the String to a Cocos2D-X String object and then calling the "intValue()" function on the String. If it is a numeric value, the function will return the value which you can use, or if it is not a numeric value, it will return 0 so it also serves for a test for numeric value, unless of course the value is "0" and you should test for that first.

int val;
String* str = String::create(“123”);
// test for 0
if(str->compare(“0”) == 0){
   val = 0;
}
else {
   val = str->intValue();
   if(val == 0){
       // String is not numeric, handle the error here
   }
   else{
       // String is numeric and its value is saved in the “val” variable
   }
}

No comments:

Post a Comment