jeudi 23 avril 2015

How to convert every element of a string to int

I am trying to get the total sum of every digit of a big number which is stored in a string variable. So the first thing to do is to convert each element to an int and add it to the total sum. So my question is how can I convert an element of a string to an int? I tried using std::stoi but I got compiler error.

Here's my code anyway:

std::string x = "7825394359371498287";
int sum = 0;
for (int i = 0; i < x.size(); ++i) {
    sum += std::stoi(x[i]);
}

Aucun commentaire:

Enregistrer un commentaire