find a digit at position in number

Ok so I dont expect anybody to just give me the answer but I just dont get this at all. Im thinking this needs to be done with some kind of loop but I have no idea which kind. Can anyone give me some insight on this program???? Thnx

Write a program that prompts for and then accepts an integer (number) from the keyboard. The program then prompts for and accepts a small integer that represents a digit position (pos) in number. The program will then find and print the digit at position pos in the number. For example, if the number entered is 12345, the program should display 2 if the user says they want the fourth (4) digit.
(Hint: 5 =345 %10 and 34=345/10 )
Last edited on
Yes, you'll need a loop. Take another look at the hint given to you.

Good luck!
Ok so here's what I have so far. I don't know how to make it work or what I'm doing wrong.
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
int main()
{
	int num = 0;
	int number = 0;
	int n = 0;
	int result = 0;


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

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

	while (n-- > 1)
	{
	num = number / (10^n-1);
	result = num % 10;
	}


	cout << "\nThe value of this digit is: " << result << endl;
	system("Pause");
	
}
^ is not a power operator in C or C++.

Remember, it is OK to modify 'number'.
ok i changed the pow part....im just not getting this...
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
#include <iostream>
#include <cmath>

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




int main()
{
	int number = 0;
	int n = 0;
	int result = 0;


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

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

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


	cout << "\nThe value of this digit is: " << result << endl;
	system("Pause");
	
}
Question: why are you doing line 31 in a loop?
I have no idea. It was based on repitition and I was told it had to be done using a loop, although I had no idea what kind of loop so thats just what I threw in there...
Woooooo...
I took the funky loop out and it works!
Thank youuuuuuu!!

One more thing....
How would I run a check for if the user enters a negative number?

Would I just use an if statement saying if its < 0 then use the absolute value?
Topic archived. No new replies allowed.