tags:

views:

150

answers:

1

Keep in mind, if you choose to answer the question, I am a beginner in the field of programming and may need a bit more explanation than others as to how the solutions work.

Thank you for your help.

My problem is that I am trying to do computations with parts of a string (consisting only of numbers), but I do not know how to convert an individual char to an int. The string is named "message".

for (int place = 0; place < message.size(); place++)
        {
            if (secondPlace == 0)
            {
                cout << (message[place]) * 100 << endl;
            }
        }

Thank you.

+3  A: 

If you mean that you want to convert the character '0' to the integer 0, and '1' to 1, et cetera, than the simplest way to do this is probably the following:

int number = message[place] - '0';

Since the characters for digits are encoded in ascii in ascending numerical order, you can subtract the ascii value of '0' from the ascii value of the character in question and get a number equal to the digit.

Amber
No cast is needed.
Tronic
That won't work on an EBCDIC machine.
Jive Dadson
@Jive - No, the C (and by extension, C++) standard guarantees that digits are consecutive. Which, in EBCDIC, they are (codes 240 through 250).
Chris Lutz
@Chris: not by extension (unless you mean historically). The C++ standard explicitly states that they are consecutive in 2.2/3.
Steve Jessop
Grrr at stackoverflow comment police. I tried to remove the comment. Couldn't do it. Tried to edit it. Slapped down again.
Jive Dadson
No worries. Rep isn't *that* big a deal. ;)
Amber
Yeah, only thing you need to do is to write cout << (message[place] - '0') * 100 << endl
pocoa