Victor Bazarov
6/17/2016 6:30:00 PM
On 6/17/2016 2:02 PM, MikeCopeland wrote:
> I'm confused about string::reverse_iterator usage.
> What I'm trying to do is scan the end of a string variable for all
> numeric digits..and then convert those digits to an integer. For
> example, I have;
> std::string myData = "cldat89";
> and I want to extract and convert the "89" to an integer variable.
> Various explanations I've found via Google aren't making sense to me,
> as they mostly assume I want to reverse the whole string data or such.
> I just want to scan backwards (from last-to-first) until a character
> _isn't_ a digit...and then be able to work with the substring of the
> digit characters.
> Although done this task "brute-force", the concept of
> reverse_iterator seemed interesting, so I wanted to try it: so far, I
> don't "get it". Please advise. TIA
When you "scan backwards", remember that the characters come in the
reverse order. So, something like this is supposed to work:
int accumulator(0);
int multiplier(1), maxnumber(100000);
std::locale defloc;
for (auto it = myData.rbegin();
it != myData.rend() && multiplier < maxnumber;
++it, multiplier *= 10)
{
char c = *it;
if (std::isdigit(c, defloc))
accumulator += (c - '0') * multiplier;
else
break;
}
(I didn't actually test this, but it should give you an idea).
V
--
I do not respond to top-posted replies, please don't ask