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;
}

Recommended Answers

All 5 Replies

For example atoi(st.c_str()).

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.

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?

This problem comes up so often, maybe we should make some sort of section for problem like these

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.