How can I get the first 5 digits in a random length integer?
For example: users input 1234567, 123456789, 1012345671
I should get 12345, 12345, 10123 respectively.
The number input by an user is not known in advance.
How can I get the first 5 digits in a random length integer?
For example: users input 1234567, 123456789, 1012345671
I should get 12345, 12345, 10123 respectively.
The number input by an user is not known in advance.
Keep dividing the number by 10 until you get something <= 99999.
If you're fairly sure that the user will enter numbers sensibly and not with e.g. leading spaces, you could just read the input as a string and get the first five characters. That's a bit of a hack though and so I also echo qwertylurker's suggestion.
Code:while(n >= 100000) n /= 10;
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.
Ok, thanks for the tip qwertylurker and dwks.