Guest
Guest

Reputation: 71

How do I convert a single char in string to an int

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.

Upvotes: 3

Views: 1834

Answers (1)

Amber
Amber

Reputation: 526723

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.

Upvotes: 6

Related Questions