HBPatrick
HBPatrick

Reputation: 15

Sum of Digits in a String (using string objects) C++

I am currently trying to take a user input string of digits, convert them individually into an int, and total their sum.

EX: If user enters "1234", program should do 1 + 2 + 3 + 4 and display "10". I have tried experimenting a lot but seem to be at a stand still.

I'm looking to create this code using C-string/String objects, and with "istringstream()" if possible (not necessary though...[esp if there are easier ways...])

Here is what I have so far:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    string digits;
    int total = 0, num;

    cout << "Enter a string of digits, and something magical will happen to them..." << endl;
    cin >> digits;

    for (int i = 0; i < digits.length(); i++)
    {   
        cout << digits.at(i) << endl;
        istringstream(digits.at(i)) >> num;
        cout << num << endl;    // Displays what came out of function
        total += num;
    }

    cout << "Total: " << total << endl;

    // Digitize me cap'm
    // Add string of digits together
    // Display Sum
    // Display high/low int in string
}

What am I doing wrong? Why do I keep getting super high numbers in the for loop? Are there more efficient functions I should be using? Thank you for any help :)

Upvotes: 0

Views: 8882

Answers (5)

Nejc Galof
Nejc Galof

Reputation: 2614

I extend previous answers with two things. I recommend using static_cast before a regular cast with (int). It is also good to ignore non-digit characters in a string to prevent crashes or wrong behavior. The final solution looks like that:

#include <iostream>
#include <string>
using namespace std;

long long sumOfDigitsInString(string digits)
{
    long long sum = 0; 
    for(auto& ch : digits)
    {
         if (isdigit(ch))
         {
            sum += static_cast<int>(ch) - 48;
         }
    }
    return sum;
}

int main() {
    string n;
    cin >> n;
    cout << sumOfDigitsInString(n);
}

Upvotes: 0

klg
klg

Reputation: 95

Assuming you have a little knowledge about ASCII (if you don't know I'll explain in the comment section):

long long sumOfDigitsInString(string n)
{
    long long sum = 0; 
    for(char& c : n) // for each char in string n
    {
         int b = int(c)-48; // this is involved in ascii
         sum += b;
    }
    return sum;
}

int main() {
    string n;
    cin >> n;
    cout << sumOfDigitsInString(n);
}

Upvotes: 0

Timo T&#252;rschmann
Timo T&#252;rschmann

Reputation: 4696

I would create a new function for getting the digit sum of any number:

long long digitSum(long long number)
{
    long long sum = 0;
    while (number != 0)
    {
        sum += number % 10;
        number /= 10;
    }
    return sum;
}

and then you can do in your main():

int main()
{
    string digits;

    cout << "Enter a string of digits, and something magical will happen to them..." << endl;
    cin >> digits;

    auto enteredNumber = std::stoll(digits);
    auto total = digitSum(enteredNumber);

    cout << "Total: " << total << endl;
}

The function std::stoll converts a std::string to long long

This will limit the number the user can enter, though. So another approach is, like other answers already said, to use the property of chars (that they are just a number).

The value of the char '0' is 48. The value of the char '1' is 49. so when you do '1' - '0' you get the result 1, which is exactly the number value of the number in char representation.

This means you can do something like this:

long long digitSum(string numberStr)
{
    long long sum = 0;
    for (int i = 0; i < numberStr.length(); i++)
    { 
        auto charValue = numberStr.at(i) - '0';
        sum += charValue;
    }
    return sum;
}

which will make your main look like this:

int main()
{
    string digits;

    cout << "Enter a string of digits, and something magical will happen to them..." << endl;
    cin >> digits;

    auto total = digitSum(digits);

    cout << "Total: " << total << endl;
}

Upvotes: 0

MichaelCMS
MichaelCMS

Reputation: 4763

Instead of istringstream(digits.at(i)) >> num , try using this way of conversion :

num = ((int)digits.at(i))-((int) ('0'));

You will have a faster code alltogether.

Upvotes: 0

Mohit Jain
Mohit Jain

Reputation: 30489

Should be

for (int i = 0; i < digits.length(); i++)
{   
    cout << digits.at(i) << endl;
    num = digits.at(i) - '0';
    assert(0 <= num && num <= 9);
    cout << num << endl;    // Displays what came out of function
    total += num;
}

To convert a single number you don't need complex things like stringstream. You can also use (not recommended) istringstream(digits.substr(i, 1))

Upvotes: 1

Related Questions