How do I split an int into its digits?

前端 未结 15 1512
渐次进展
渐次进展 2020-11-27 17:51

How can I split an int in c++ to its single numbers? For example, I\'d like to split 23 to 2 and 3.

15条回答
  •  春和景丽
    2020-11-27 18:00

    int n = 1234;
    std::string nstr = std::to_string(n);
    std::cout << nstr[0]; // nstr[0] -> 1
    

    I think this is the easiest way.

    We need to use std::to_string() function to convert our int to string so it will automatically create the array with our digits. We can access them simply using index - nstr[0] will show 1;

提交回复
热议问题