Split an Integer into its digits c++

后端 未结 12 1843
说谎
说谎 2020-11-28 15:27

I\'m trying to learn c++ on my own and I\'ve hit a bit of a road block. The problem is I need to take an integer,split it into its digits and get the sum of the digits and

12条回答
  •  [愿得一人]
    2020-11-28 16:22

    Let's not forget the stringstream approach, which I also find elegant.

    #include 
    #include 
    
    int main()
    {
        int num = 123456789;
        std::cout << "Number: " << num << std::endl;
    
        std::stringstream tmp_stream;
        tmp_stream << num;
        std::cout << "As string: " << tmp_stream.str() << std::endl;
    
        std::cout << "Total digits: " << tmp_stream.str().size() << std::endl;
    
    
        int i;
        for (i = 0; i < tmp_stream.str().size(); i++)
        {
            std::cout << "Digit [" << i << "] is: " << tmp_stream.str().at(i) << std::endl;
        }
    
        return 0;
    }
    

    Outputs:

    Number: 123456789
    As string: 123456789
    Total digits: 9
    Digit [0] is: 1
    Digit [1] is: 2
    Digit [2] is: 3
    Digit [3] is: 4
    Digit [4] is: 5
    Digit [5] is: 6
    Digit [6] is: 7
    Digit [7] is: 8
    Digit [8] is: 9
    

提交回复
热议问题