I have an int i, say 6473, and I want to store each digit separately in an array, like so:
array[0] = 6;
array[1] = 4;
array[2] = 7;
araay[3] = 3;
How can I do this?
thx
I have an int i, say 6473, and I want to store each digit separately in an array, like so:
array[0] = 6;
array[1] = 4;
array[2] = 7;
araay[3] = 3;
How can I do this?
thx
What have you tried?
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
I know how to declare an array, I just don't know how to split an int into an array.
Suppose you divide the number by 10. What is the remainder?How would I access each individual digit of the number
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Admittedly, it's possible without a string, but a bit tricky. Here's an example!
num1 = 5, num2 = 4, num3 = 3, num4 = 2, num5 = 1Code:const int mynum = 12345; int num1 = ( mynum - (mynum / 10 * 10) ) / 1; int num2 = ( mynum - (mynum / 100 * 100) ) / 10; int num3 = ( mynum - (mynum / 1000 * 1000) ) / 100; int num4 = ( mynum - (mynum / 10000 * 10000) ) / 1000; int num5 = ( mynum - (mynum / 100000 * 100000) ) / 10000;
Might I suggest sprintf()...
Code:char str[12]; int num = 12345; sprintf( str, "%d", num );
Actually, it's not very difficult to do your own as long as you store the string from the back. But obviously much less code to use sprintf() [at least of code "that you write yourself"].
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.