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>
usingnamespace 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 (unsignedint 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;
}
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?
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.