Getting each digit from a number into it's own element

Aug 29, 2013 at 2:23am
I was working on a binary to decimal converter. I have an algorithm I understand but I'm stuck at this part:

1. Read in a number: i.e. 52689
2. Store each digit in it's own element in a vector

So if the user enters 52649 in 1 single input, each digit is in it's own element in a vector and becomes:

[0] = 5, [1] = 2, [2] = 6, [3] = 8, [4] = 9.

Can someone please give me some guidelines please?
Last edited on Aug 29, 2013 at 2:26am
Aug 29, 2013 at 2:30am
closed account (N36fSL3A)
An easy solution would be just to get a string as the input, and check if each character is a numerical value.

Then you can just convert each character to an actual integer.
Aug 29, 2013 at 2:47am
Do you mean by static_cast?

Edit: It implicitly converts it already, no need for a cast.
Last edited on Aug 29, 2013 at 2:58am
Aug 29, 2013 at 2:49am
Try reading in to a string
Then adding each character of the string to the vector maybe?

1
2
3
std::getline( std::cin , str );
for( const auto &it : str )
vec.push_back( *it );


Something along those lines maybe.
Aug 29, 2013 at 3:05am
Yes this worked thanks. I could've sworn I did something before that convinced me you can't get ints from a string but ofcourse you can through char conversions!

One small thing though, through the conversion, ofcourse I actually get the ANSII values of the numbers - is there a simple way that when I extra a char>int from a string, it gives me the actual number represented by the ASCII code there and then? Or should I just do some loop like "if some ASCII, then element = <there number it represents>"?
Last edited on Aug 29, 2013 at 3:06am
Aug 29, 2013 at 3:06am
I have a feeling that they're going to end up doing math or some kind of operation with each number. Your example would still have characters, or at least character values.

My suggestion is to read it in as a long, use the modulo operator to break each number off, and store it into an item of a vector. You may need to tweak it to get your vector the way you want it to be, but it's pretty simple.
Aug 29, 2013 at 3:07am
- '0'
or - 48 I think.
or you could cast it
static_cast<int>( some_char );
( int )some_char;

I would just - '0' but it might not be the best way.

here's an example
1
2
3
char ch = '9';
int i = ch - '0';
if( i == 9 ) std::cout << " i == 9 " << std::endl;
Last edited on Aug 29, 2013 at 3:09am
Aug 29, 2013 at 3:44am
Thanks guys for the replies, I got the idea what to do now. I just realised I worded some of this wrong too, obviously I'm only dealing with 1s and 0s, not 1-9!
Topic archived. No new replies allowed.