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.
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.
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.