problem with a reverse iterator

B

brad

In the example below, possible_number is a string of one or more
digit(s). For example, it may be 4 or 4444. However, when I attempt to
perform the times 2 calculation, the ASCII value of 4 (which is 52) is
used instead of 4 itself. I need to be able to easily reverse the order
of the digits and to only perform this calculation on even positioned
digits... that's why I'm using string instead of int. Any suggestions on
how to make 4*2 = 8 I've tried atoi() type casting, etc. I'm stuck.
Still learning c++.

Thanks for any help!

int position = 0;

string::reverse_iterator rit;
for (rit=possible_number.rbegin(); rit < possible_number.rend(); rit++)
{
if (position % 2 == 0)
{
// Here's the problem *rit * 2 = 104, not 8
cout << position << *rit * 2 << endl;
position++;
}
}
 
B

brad

Victor said:
An element of a string is of type 'char'. As you have found out
already, the value is controlled by the encoding of the symbol.
If you want to convert a char that supposedly contains a decimal
digit into its corresponding number, you need to (a) test to see
that it's actually a digit (see 'isdigit' function) and (b) if it
is a digit, subtract '0' from it:


if (isdigit(*rit))
cout << position << (*rit - '0') * 2 << endl;
else
cerr << position << " - not a digit!!!" << endl;


V

Wow. That works. I do not fully understand why it works, but I wanted to
thank you for the advice. I'll research it more until I better understand.

Brad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,172
Messages
2,570,933
Members
47,472
Latest member
blackwatermelon

Latest Threads

Top