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

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
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.
Do you mean by static_cast?

Edit: It implicitly converts it already, no need for a cast.
Last edited on
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.
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
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.
- '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
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.