ofToInt, ofHexToInt, etc don't offer warnings or exceptions if string is malformed. #1968

Open
bakercp opened this Issue Mar 25, 2013 · 4 comments

Projects

None yet

3 participants

@bakercp
Member
bakercp commented Mar 25, 2013

When converting strings to numbers using the ofXToY(...) functions, no errors or warnings are throw if the conversion wasn't successful.

For example:

int x = ofToInt("123abc"); returns 123.
int x = ofToInt("abc123"); returns 0.

While in some cases, it's nice to use this "feature" for parsing numerical prefixes, it can be a bit confusing. This is, of course, expected behavior using std::istringstream, and in fact, it's somewhat similar to how javascript's parseInt() works (with the exception that parseInt() will return NaN for string prefixes. In Processing the int() function wraps Integer.parseInt() and (usually) just ignores the NumberFormatException, so it's not too different from the Processing experience either. But I think we can do better in oF and propose that we (at the very least) log a warning if there was a parse error. A solution for ofToInt might look like:

int ofToInt(const string& intString) {
    int x = 0;
    char c = 0;
    istringstream cur(intString);
    if (!(cur >> x) || cur.get(c)) {
        ofLogWarning("ofToInt") << intString << " converted to " << x;
    }
    return x;
}

We could, of course, make the warning optional.

This is a slight mod of this solution: http://www.parashift.com/c++-faq-lite/convert-string-to-num.html

@kylemcdonald
Contributor

good catch. i'd agree that we can do better than processing, and we should -- so any fix for this is welcome. i don't see these functions as "very optimized", but they should be "very correct". using warnings could get really frustrating really quickly though.

@bakercp
Member
bakercp commented Mar 25, 2013

I agree with the warning-spew producing situation. But in the absence of Exceptions in in the oF style, it seems that a different method signature with a "success" var of some kind would be the next option?

@bilderbuchi
Member

I have to say I never really understood why we don't want to use exceptions in OF.

@bakercp
Member
bakercp commented May 8, 2013

Alternatively, I'd propose we just use Poco's parsing.

http://pocoproject.org/docs/Poco.NumberParser.html

It throws http://pocoproject.org/docs/Poco.SyntaxException.html on failure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment