Is it possible to point to a certain index of a value? For example, int x = 2576, is it possible to do something like x[2]? I know you can do it with strings, but can you do it with numbers?

Recommended Answers

All 2 Replies

Possible, but not directly. The two options are basically to convert the number to a string and index that, or write a function that separates the number arithmetically and returns the digit at the selected index.

Edit:

Just for giggles, here's a fun example. :)

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>

class CoolInt {
public:
    CoolInt(int value, int base = 10)
        : _value(value), _negative(value < 0)
    {
        if (value == 0)
            _digits.push_back(0);
        else {
            value = abs(value);

            while (value) {
                _digits.push_back(value % base);
                value /= base;
            }

            std::reverse(_digits.begin(), _digits.end());
        }
    }

    operator int() const { return _value; }
    int operator[](unsigned index) { return _digits.at(index); }

    bool negative() const { return _negative; }
    int size() const { return _digits.size(); }
private:
    std::vector<int> _digits;
    int _value;
    bool _negative;
};

int main()
{
    CoolInt x(12345);

    std::cout<<"x is "<< (x.negative() ? "negative" : "positive") <<'\n';

    for (int i = 0; i < x.size(); ++i)
        std::cout<< x[i] <<'\n';
}

Awesome, thank you for the quick answer. :)

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.