I need to find a digit at a specific postion in a number. Example number 652796, user inputs a 4, "2" is displayed.
I have the basis for it, but most of the time, the output is incorrect. Not sure what's wrong.

#include <iostream>
#include <cmath>

using std::cout;
using std::cin;

int main ()
{
    int number = 0,
        digits = 0,
        position = 0,
        result = 0;

    cout << "Enter a number: ";
    cin >> number;

    cout << "Enter a digit position:";
    cin >> position;


    if ( 0 == number)
        {
         cout << "0";
        }

    while (position-- > 1)
    {
    number = number / pow(10,position);
    result = number % 10;
    }

    cout << result <<'\n';

    return 0 ;
}

line 26 has two problems:

position should not be decremented on line 26, decrement it after line 29.

the loop should continue while position > 0 instead of > 1.

You don't need the while loop. Just decrememt postion as the loop does, then do the divide and modulus and ... voila.

Well, that works when the position given is actually within the number. Do you need to handle the case of user asking for 7th position of a 3 digit number?

This question has already been answered. Start a new discussion instead.