Search code examples
c++stringobjectsumc-strings

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 :)


Solution

  • 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))