a simple task

Jan 26, 2011 at 8:57pm
Guys please give me a hint.
The task is how to divide a variable into parts.
For example an user inputs number 34559.
I have to print it as:3 4 5 5 9
and i have no idea how to break this variable into five pieces.
Thanks a lot in advance.
Jan 26, 2011 at 9:09pm
Hint: Use the modulus operator.
Jan 26, 2011 at 9:17pm
Jan 26, 2011 at 9:38pm
you'll also need a dynamic storage container for the numbers you extract, since you might not know the amount of characters you'll need to store beforehand.

http://cplusplus.com/reference/stl/vector/

that is provided that you want to store each part and not just print them out
Jan 27, 2011 at 10:23am
You can first convert this integer into a string and store it in a char buffer using sprintf(). Then you can access each number by index of the char array.

1
2
3
4
5
int number = 12345;
char buffer[10]; //size of buffer  depends on the maximum possible digits for the integer
printf(buffer, "%d", number);
for(int i = 0; i<strlen(buffer); i++)
     cout<<buffer[i]<<" ";


Please note that this is not the most efficient way
Last edited on Jan 27, 2011 at 10:25am
Topic archived. No new replies allowed.