C++ get each digit in int

前端 未结 13 1351
谎友^
谎友^ 2020-12-02 21:50

I have an integer:

int iNums = 12476;

And now I want to get each digit from iNums as integer. Something like:

foreach(iNum          


        
13条回答
  •  甜味超标
    2020-12-02 22:13

    Drawn from D.Shawley's answer, can go a bit further to completely answer by outputing the result:

    void stream_digits(std::ostream& output, int num, const std::string& delimiter = "")
    {
        if (num) {
            stream_digits(output, num/10, delimiter);
            output << static_cast('0' + (num % 10)) << delimiter;
        }
    }
    
    void splitDigits()
    {
        int num = 12476;    
        stream_digits(std::cout, num, "-");    
        std::cout << std::endl;
    }
    

提交回复
热议问题