counting the digits of nums

Hi.
I'm not a native, sorry if something is wrong with the writings.
I have two problems with this program.
the first one is with countOfDigit function. when I enter a number that has more than 12 digits, it return 12 as the number of digits. when I tracked the program I understood that after the 12th division, it outputs "inf". how should I stop this?
the second problem is with digitsOfNum function. It should return the number in the specified range. for example if you enter 123456, 2, 3 it should return 345 but it returns 543!

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <math.h>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
using namespace std;

int countOfDigit(double);
int digitsOfNum(int, int, int);

int main()
{
    int numb, start, lentgh;
    cout << "Please enter the number, the starting point and the length"; 
    cin >> numb >> start >> lentgh;
    cout << digitsOfNum(numb, start, lentgh);
}

int countOfDigit(double num)
{
    int digits = 0;
    for(int i = 10; i != 0 ; i *= 10)
    {
        digits++;
        if ((num / i) < 1)
        {
            i = 0;
        }
    }
    return digits;
}

int digitsOfNum(int num, int start, int lentgh)
{
    int cot = countOfDigit(num);
    vector<int> digit(cot);
    vector<int> digi(cot);
    digit.resize(cot);
    for(int i = 0; i < cot; i++)
    {
        int a = num % 10;
        digit[i] = a;
        num = num / 10;
    }
    for(int i = cot - 1; i >= 0; i--)
    {
        digi[i] = digit[(cot - 1) - i];
    }
    int finalNum = 0;
    for(int i = 0; i < lentgh; i++)
    {
       finalNum += digi[start + i] * pow(10, i);
    }
    return finalNum;
}
the first one is with countOfDigit function. when I enter a number that has more than 12 digits, it return 12 as the number of digits. when I tracked the program I understood that after the 12th division, it outputs "inf". how should I stop this?


The only way is to use a variable type that can handle more than 12 digits.
Some examples are:
1
2
3
4
5
6
7
8
9
long long int
unsigned long long int
std::string
char*
//From <ratio>: http://www.cplusplus.com/reference/ratio/ratio/?kw=ratio
std::tera
std::peta
std::exa
//etc. 

Or as some programmers here may suggest, writing your own BigInt class. But unless you need 1000 digit numbers or something, just use the available types.


the second problem is with digitsOfNum function. It should return the number in the specified range. for example if you enter 123456, 2, 3 it should return 345 but it returns 543!


Try reversing the order you store the numbers in the vector (or reverse the order you combine the digits).
thanks
Topic archived. No new replies allowed.