Hi, i've tried look about for this but cant find it.
Basically all i want to do its break a number up into single ints.
I.E
id have
int a
int b
int c
and a number, say 189. I want break 189 into 1,8 and 9. So a=1 b=8 and c=9.
thanks for any help.
This is a discussion on Stupid easy noob question. within the C++ Programming forums, part of the General Programming Boards category; Hi, i've tried look about for this but cant find it . Basically all i want to do its break ...
Hi, i've tried look about for this but cant find it.
Basically all i want to do its break a number up into single ints.
I.E
id have
int a
int b
int c
and a number, say 189. I want break 189 into 1,8 and 9. So a=1 b=8 and c=9.
thanks for any help.
Use math, specifically division and modulus. What's (189 / 100) % 10 in integer math? It's 1. What's (189 / 10) % 10? It's 8. What's (189 / 1) % 10? It's 9.
Last edited by Daved; 04-10-2008 at 02:12 PM. Reason: Thanks Todd
oh, so i cant just break it up you can in java?
If "189" is a string, then yes you can parse it out. You implied 189 was an integer by calling it a number, (and because you didn't put double quotes around it), thus you got a math solution.
Mac and Windows cross platform programmer. Ruby lover.
Quote of the Day
12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.
Amen brother!
Of course you can, and Daved explained how.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.
yeah it is an int i will be reading in.
so there is no classes to do this sort of thing? sorry im a noob at c++
in java i would just use the scanner and nextInt()
thanks for the replys.
No, you wouldn't do that in Java, as nextInt() only works with strings (you said it's an int) and would grab the entire number.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
Or the std::stringstream class would work.
>> yeah it is an int i will be reading in
Or you might be able to read it in as a string and get each digit that way. To convert a single character to an int just subtract the zero character:Code:string num("189"); int second_digit = num[1] - '0'; // second_digit is 8.