Sunday, August 2, 2009

In C++ how do you convert an integer to an array of integers?

For example, if the user inputs the value 4637 for "int n", how do i convert that into an array of integers "int * a", where a[0] = 4, a[1] = 6, a[2] = 3, and a[3] = 7 ?





(you can assume "int * a" has been declared a "new int", i realize the length of the array is not known at compile time)

In C++ how do you convert an integer to an array of integers?
its so easy:-


// scan the number


scanf("%d",%26amp;n);


//initialize the array


int a[10];


// i assume the number shouldnt be a large value


k=0;


//for loop


for(int i=1;(n%i)!=0;i=i*10)


{ a[k++]=(n%i);


}


for example if your no is n=4637


then for first pass, n%1 =7 therefore a[o]=7


for second pass, n%10 =3 therefoe a[1]=3


for third pass, n%100 =6 therefoe a[2]=6


for fourth pass, n%1000 =4 therefoe a[3]=4


after this, the for loop ends.
Reply:%26lt;outdated text have been removed%26gt;


Ok, scanf here has nothing with the actual algorythm - it is used only to receive input from user. Just replace it with "cin %26gt;%26gt; n;" or whatever way to receive user input into "n" you like and everything will work as perfect as it was with "scanf".





BTW, as "scanf" itself is not very useful for modern application, its memory version "sscanf" can be a very good choice when you need to parse a string: it allows developer to precisely specify what should be read from the string and in what format. I think that you will not regret if you learn this function and its format strings (at least the most basic ones).


GL.


No comments:

Post a Comment