Please I need help having this compiled



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
Return the digit at the user specified index of an integer.  If the integer has n digits and the index is NOT in the range 0 <=index  <n  return -1   Start the digit numbering at 0.  Example,  if user input  is  4 (index) and the integer equals 123456790  the return value for the function is 5  (start index at 0) ;    if user input  is  40 (index) and the integer equals 123456790  the return value for the function is -1  



#include <iostream>
#include <istream>
#include <cstdlib>
#include <cassert> 
#include <string>
using namespace std;

int getIndex(int, int);
int main()
{
	int index = 0;
	int i = 0;
	cout << "Enter integer ";
	cin >> i;    	// 123466  sample user input 
	cout << "Enter index ";
	cin >> index;    	// 4 sample user input 
	
	cout << " The digit at index " << index << " is " << getIndex(index, i) << endl;

	system("pause");
	return 0;
} // main function finishes.

int getIndex(int index, int number )
{
	int returning = 0;
	int counter = 0;
	while (number)
	{
		number = number / 10;
		counter++;
	}
	cout << counter << endl;
	for (unsigned int i = 0; i < counter; counter--)
	{
if (number.at(i) == index)  // This is where I’m basically stuck  .at() didn’t compile 
	returning = counter;
	else
	returning = -1;
	}
	return returning;

}

Well, let me make your life much, much easier:

Take the user input as a string. Yes, it is a number. However, for a problem like this, you would be much better off dealing with strings as character arrays- that way, you could just say something like i[index] for the digit rather than having to do all of this other stuff.

Also, .at(i) won't work here. What you want to do is modulus division by 10- if it isn't equal, divide the whole thing by 10.
Yeah unfortunately, the labs requests a pass by value to an integer. Otherwise, if it was a string as you said, It would have been easier.

I've done the modulus division ( N = number%10 ) but there the count will start from the opposite side(integer leftover), thus It will not give me the exact index. What you think?
Last edited on
You will have to work backwards for this. There's no way to get a value starting at the largest digit- not unless you do some horrible modulus-division tree thing that would just be abysmal. You'll have to...

Wait. You could create a second number that is the exact reverse of the first, then use the index that way.
Oh yes. many many thanks. reversing it and then comparing the left from integers.
thank you for you help :)
Topic archived. No new replies allowed.