Daedaluss
Daedaluss

Reputation: 13

Int into Array C++ help please

I am trying to separate an integer into an array. I have been using modulo 10 and then dividing by 10 but I believe that will only work for numbers 6 digits or less I may be wrong but it is not working for me. This is what I have:

for(int i=0; i<=8; i++){ 
    intAr[i] = intVal%10;
    intVal /= 10;
}

It is not working for me and help would be lovely

Upvotes: 0

Views: 95

Answers (2)

Zac Howland
Zac Howland

Reputation: 15872

If you are expecting the numbers to be stored in your array right-to-left, you'll need to reverse the way your store the values:

for(int i=0; i < 9; i++)
{ 
    intAr[9 - i - 1] = intVal % 10;
    intVal /= 10;
}

This will store your number (103000648) like this

|-0-|-1-|-2-|-3-|-4-|-5-|-6-|-7-|-8-|
| 1 | 0 | 3 | 0 | 0 | 0 | 6 | 4 | 8 |

instead of

|-0-|-1-|-2-|-3-|-4-|-5-|-6-|-7-|-8-|
| 8 | 4 | 6 | 0 | 0 | 0 | 3 | 0 | 1 |

Upvotes: 1

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

The problem i guess you have is that the number in the array is reversed. So try this:

for(i=8;i>=0;i--)
{
    intAr[i] = intVal%10;
    intVal /= 10;
}

This will work and have the number stored correctly in the array

Upvotes: 2

Related Questions