0

i'm trying to write a function which takes one int parameter and returns sum of it's digits.For example, digital_root(123) will return 1+2+3 which is 6.And inside the for loop i can't convert individual character to integer..

it should be included that i used both atoi() and stoi() functions.What is wrong with the code?

int digital_root(int x)
{
    int t = 0;
    string str = to_string(x);
    for(char& c : str){
        t += atoi(c);
    }
    return t;
}

i expect the characters to convert to integer successfully.how can i do so?

user32350
  • 13
  • 1
  • 7
    You don't need to introduce or use any strings to add up the digits. Think about division by 10 and modulus. – PaulMcKenzie Jun 20 '19 at 10:15
  • What is the problem? Did you get an error? Exception? Your question is not so explicit. – BiagioF Jun 20 '19 at 10:17
  • https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in – Dan M. Jun 20 '19 at 10:17
  • If you insist to use string-way to do calculation, may be the `str.substr(i, 1)` can be accepted by atoi()/stoi(). – Chen OT Jun 20 '19 at 10:40
  • Is there other convenient function that i could have used? Why using strings is a bad idea? – user32350 Jun 20 '19 at 12:57
  • @user32350 The convenient function is a simple `while` loop, dividing by 10 and summing the remainder. Very fast.. Using strings requires a conversion from the int to a string, which is a tiime waster. – PaulMcKenzie Jun 20 '19 at 15:23
  • [See how simple it is?](https://coliru.stacked-crooked.com/a/1b8510df565f663b) – PaulMcKenzie Jun 20 '19 at 15:30

1 Answers1

1

Have a look at std::atoi, its argument is of type const char*, but you are passing a single char. There is no possible conversion from char to const char*, this is what the compiler complains about.

What you want instead is converting the char to an int by doing some ASCII math:

t += static_cast<int>(c)  - '0';

But note that while this works, there is a better solution for this task. It doesn't require the conversion to a string, but instead relies on integer division solely, repeatedly using % 10.

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • Is there a way to get char type through for loop ? – user32350 Jun 20 '19 at 12:41
  • I dont't get that question, the loop variable is already of type `char&`?! – lubgr Jun 20 '19 at 12:42
  • As you said i need const* char type to use atoi and stoi function . So how should i change my for loop so that i can work with const* char rather than char? (I mean c variable as a const* char) – user32350 Jun 20 '19 at 12:50
  • Well you could convert each single `char` into a null-terminated string, and then pass `std::string::c_str()` to `atoi`. But note that while this might work, it makes absolutely no sense to do such a thing. And iterating over `const char*` isn't possible because a `std::string` is a sequence of `char`, not of `const char*`. – lubgr Jun 20 '19 at 12:53