my vector only takes in 10 digits how can i make it more?

89 Views Asked by At

I've been playing with a bit of code, trying some stuff, and I wanted to make a program that could take in any amount (or at least 100) digits of numbers and then add them up, but ti my dismay, it only shows 10 for some reason, and I'm not sure why. I've tried a lot of stuff, which hasn't helped.

I've tried changing the size of the vector, making the int into long long int, or trying something from the internet, but nothing helped.

#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int main()
{
    vector<long long int> number;
    long long int av;
    cin >> av;
    for (int i = 0; i != 342; i++) {
        double fool = pow(10, i);
        int lol = int(fool);
        long long kik = (av / lol);
        int c = kik % 10;
        if (c > 0)
            number.push_back(c);
    }
    int hah = 0;
    for (int j = number.size() - 1; j >= 0; j--) {
        if (number[j] > 0) {
            cout << number[j] << endl;
            hah = hah + number[j];
        }
    }
    cout << hah << endl;
}
1

There are 1 best solutions below

0
Chris On

You want to read in a very large number, and then add up its constituent digits. I think you have an XY problem here. There is no type that is going to hold an int with hundreds of digits. That's a big number: the largest number a 64-bit unsigned int can store is 18446744073709551615 which has twenty digits.

Instead use a string, then iterate over its digits, convert them to very small ints, and sum them.

E.g.

#include <iostream>
#include <cctype>
#include <string>

int main() {
    std::string in;
    std::getline(std::cin, in);

    unsigned int sum = 0;

    for (auto c : in) {
        if (!std::isdigit(c)) {
            std::cerr << "Non-digit char encountered." << std::endl;
            return 1;
        }

        sum += c - '0';
    }

    std::cout << "Sum is " << sum << std::endl;

    return 0;
}