Splitting an integer into a vector of its digits

I'm currently working my way through "C++ principles and practice" by Bjarne Stroustrup, and as one of the exercises I have to work with individual digits of an integer. I did some research on the web, but couldn't really find anything except to make use of strings. Since I haven't officially learned to work with streams I decided to do it another way. My question is, how can this be done easier? It took me a few hours to get this to work properly, and I'm sure there's an easier way to do this. Are there any in-built functions that could do this?

From my little experience with Java I'm pretty sure doing this with strings would have been easier.

here's my solution:
This function takes an integer, and returns a vector with the individual digits.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

vector<int> extDig(int n){
	
	bool first;
	int mod, div=1;
	int sum=0, cur=0;
	int digs = getDig(n); //getDig returns the number of digits of an int
	vector<int> d(digs);

	for(int k=0; k<digs; k++){

		first=true;
		mod = (int)pow(10.0, digs);
		for(int i=0; i < digs-k; i++){
			if(first){
				d[k] = n % mod;
				mod /= 10;
				first = false;
			}else{
				d[k] %= mod;
				mod /= 10;
			}
		}

		for(int j=0; j < cur; j++){
			sum += (int)(d[j] * pow(10.0, j-1));
		}

		d[k] = (d[k] - sum) / div;

		div *= 10;
		cur++;
	}

	//reverse vector
	vector<int> v(digs);
	for(int i=0; i<v.size(); i++){
		v[i] = d[digs-(i+1)];
	}
	return v;
}




Please excuse the fact that there's so many nested loops and ifs, this is after all the beginners forum. :)
Also, the book uses a custom header file, so I'm not sure everything is standard.
Last edited on
Yes, you can streamstring it.

1
2
3
4
5
6
7
vector<char> intotvec(int tovec){
    stringstream ss;
    ss << tovec;
    string tmp = ss.str();
    vector<char> tmv(tmp.begin(),tmp.end());
    return tmv;
}
That certainly is a lot shorter. I didn't know you could create a vector like that on line 5.

Thanks
d is reversed, ¿right?
1
2
3
int mod = 10;
for( ; n>0; n/=mod)
  d.push_back( n%mod );
It will need to handle the special case where n==0
Last edited on
ne555, I'm not sure what you mean with that code. However I have figured out that my code is fairly useless, as it doesn't properly handle the case where n == 0. In fact, if given a integer like 000, it's completely off as it takes 0 as a parameter. I have thus decided to go with the string method, which doesn't seem to have these problems at all.
Topic archived. No new replies allowed.