Hi, I've been trying to create a C++ program that gets the input from the user, calculates the amount of digits in the array and then calculates the sum of the digits

Heres what i've got so far

int main()
{
    char num[100];


    cout << "\nEnter Number: ";
    cin >> num;

    int counter = 0;
    for (int i = 0; num[i] != '\0'; i++)
        counter += 1;


    cout << counter << endl;

    int sum = 0;
    for (int a = 0; num[a] != '\0'; a++)
    {     
        num[a] = num[a] = '0';
        sum += num[a];
    }

    cout << sum;

    return 0;
}

but i cant seem to find the sum of the digits

Dani AI

Generated

Good quick fix from — the original program was counting characters correctly but then accidentally treated those characters as literal characters (and even overwrote them), so the code ended up summing character codes instead of numeric digits. Converting each digit character to its numeric value before adding is the right idea.

Practical, robust checklist to apply now:

  • Prefer reading into a std::string rather than a fixed char buffer to avoid overflow and to get length directly (std::string).
  • Skip an optional leading sign (+ or -) if you only want digits.
  • For each character, test that it is a digit with std::isdigit and cast the argument to unsigned char to avoid undefined behavior on some platforms (std::isdigit). If it is a digit, map the character to its numeric value by subtracting the code for '0' (this maps '0'..'9' to 0..9) and accumulate that into your sum. If a non-digit appears, decide whether to treat that as an error or to ignore it.
  • Use std::size_t for the digit count. The sum of digits fits comfortably in an int for typical inputs, but pick a wider type if you expect extremely long numbers.

Example behaviours worth testing: plain numbers, numbers with leading sign, inputs with embedded non-digits, and empty input. For further details on character classification and the contiguous digit codes that make the subtraction trick work, see the two references above and the ASCII table.

Recommended Answers

All 2 Replies

>num[a] = num[a] = '0';
= is not the same as -. One is assignment, the other is subtraction. This is the line you want that will give you the correct sum:

num[a] = num[a] [B][I]-[/I][/B] '0';

Wow, thanks heaps Narue

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.