Search code examples
c++c++11numbersintegerdigits

Finding a number at a particular digit in a number


I want to get number present at the specific index.

Suppose the number is "123456789" and i need to return the number at position 3 from left.

Should I convert this number to a string and re-convert the char at specific index to integer to get the number value?

Is there any inbuilt function to do so in C++?


Solution

  • This should return the third digit that of a number!

    cout << "Enter an integer";
    int number;
    cin >> number;
    int n = number / 100 % 10
    

    Or (for all digits):

     int number = 12345;
     int numSize = 5;
    for (int i=numSize-1; i>=0; i--) {
      int y = pow(10, i);
      int z = number/y;
      int x2 = number / (y * 10);
      printf("%d-",z - x2*10 );
    }