Hey!
I'm trying to convert digits separated from each other in a vector into a number, for example if I have 1, 3, and 9 in a vector I want to turn that into the number 139. But my code always seems to return the desired number minus 1, so it returns 138 instead of 139, and 222 instead of 223 and so on. Can you help me? Here is my code:
(I'm not using it for the purpose of just printing it out, because then I could've used the vector.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <vector>
#include <cmath>
usingnamespace std;
int main(){
vector<int> number = {1,3,0};
int n = number.size()-1, sum = 0;
for(int x=0;x<number.size();x++){
sum += number[x]*pow(10,n);
n--;
}
cout << sum << endl;
}
#include <iostream>
#include <vector>
#include <limits>
int main()
{
const std::vector<int> digits = { 1, 3, 0, 9, 8, 7, 2, 5 } ;
// if the vector conatains more digits than the guaranteed number of decimal digits
// that can be represented by the type int, give up and report an error
// see: http://en.cppreference.com/w/cpp/types/numeric_limits/digits10if( digits.size() > std::numeric_limits<int>::digits10 )
{
std::cerr << "possible overflow\n" ;
return 1 ;
}
int number = 0 ;
for( int v : digits ) // for each value in the vector
{
if( v<0 || v>9 ) // if the value is not that of a valid decimal digit
{
std::cerr << "invalid decimal digit\n" ;
return 1 ;
}
number *= 10 ; // add a zero at the end of the current value
number += v ; // and add the new digit
// for example: if the current value of number is 1309
// and the next digit is 8
// 1309*10 + 8 == 13090 + 8 == 13098
}
std::cout << number << '\n' ;
}
Thanks for the answers everyone! I think I got it working now, however when inputting it into my program it doesn't work :( Must have done something else wrong