openframeworks / openframeworks/openFrameworks
ofToInt, ofHexToInt, etc don't offer warnings or exceptions if string is malformed.
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 10.4k
- Forks
- 2.6k
- Avg merge
- 1d 21h
- Merged PRs (30d)
- 9
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the ofToInt, ofHexToInt, and related ofXToY conversion entry points, then inspect how malformed input is currently handled. Clarify whether warnings or exceptions are required and whether prefix parsing remains supported; done means the chosen behavior is consistent across conversions and covered for inputs such as "123abc" and "abc123".
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- api
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100