How would I convert a string to an integer? I found a method online, but I don't really know how it works. The method is subtracting the character '0' from the character. Supposedly, this makes it an array, but I do not know why. Can anyone explain why? And are there any other methods of approaching this?

A short program using the method I found online:

#include <iostream>

using namespace std;

int main()
    string st = "12345";
    int sum = 0;
    for(int i = 0; i < st.size(); i++)
        sum += (st[i] - '0');

    cout << sum;
7 Years
Discussion Span
Last Post by frogboy77

You can use std::stringstream . For example:

#include <string>
#include <sstream>
#include <iostream>

int main () {
    std::string s = "12345";
    std::stringstream ss(s);
    int value = 0;

    std::cout << "value before: " << value << std::endl;

    ss >> value;

    std::cout << "value after : " << value << std::endl;

    return 0;

Of course, error checking is not present in the above example and you would need to provide some to verify the result you got.

Another method would be to use strtol on the std::string.c_str () result.

Edited by L7Sqr: n/a


Each character has a numeric value
'A' = 65
'B' = 66
'0' = 48
'1' = 49
and so on.

Subtracting '0' subtracts 48, so '2' - '0' = 2 , equivalent to 50 - 48 = 2 Now look at the code you posted. Does that shed any light on the subject?


Surely the method mentioned by the OP would show sum to be 15.
This is not is what you are looking for(at least i think).
stringstream may be the way to go.

Edited by frogboy77: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.