I am trying to take a user entered integer (positive or negative) and let them pick a digit position and output the digit at that position.
int findDigAtPos(int number)
{
int position;
int result;
cout << "Enter digit position between 1 and " << std::to_string(number).length() << endl;
cin >> position;
while (position < 0 || position > std::to_string(number).length())
{
cout << "Enter digit position between 1 and "<< std::to_string(number).length()<<endl;
cin >> position;
}
if (std::to_string(number).length() == 1)
cout << "Only one digit" << endl;
number = number / pow(10, (position - 1.0));
result = number % 10;
return result;
}
This is the code I currently have for the function. However, it outputs the number in reverse. How do I correct the digit position? I thought it didn't even function correctly until noticing it's in reverse order.
CodePudding user response:
Instead of this:
number = number / pow(10, (position - 1.0));
result = number % 10;
This:
int length = (int)(std::to_string(number).length());
while (position < length)
{
number = number / 10;
length--;
}
result = number % 10;
The above should work fine for positive numbers. For negative numbers, you might need to a fixup. I'll leave that as an exercise for you to manage.
CodePudding user response:
First, note that you shouldn't be using the pow
function when working with integers, because it returns a double
result, which can cause problems due to unexpected truncation of the result.
But, if you insist on using it, then you need to remember that the power of 10 by which to divide will decrease as the digit position increases: i.e., the position is given with the leftmost (most significant) digit in position 1. Thus, that power of 10 will be total number of digits minus the position:
number = number / pow(10, (std::to_string(number).length() - position));
result = number % 10;
The safer method (not using pow
) would be a small loop, like this:
for (int d = std::to_string(number).length() - position; d > 0; --d) number /= 10;
result = number % 10;
However, as you're already converting the passed number to a string, then why not just save that string and extract the digit from it – at position-1
, because array (and string) indexes in C are zero-based:
int findDigAtPos(int number)
{
int position;
std::string str = std::to_string(std::abs(number)); // If -ve, remove sign!
int ndig = str.length();
std::cout << "Enter digit position between 1 and " << ndig << "\n";
std::cin >> position;
while (position < 0 || position > ndig) {
std::cout << "Enter digit position between 1 and " << ndig << "\n";
std::cin >> position;
}
return str.at(position-1) - '0';
}
Note that the numeric digits, 0
thru 9
are guaranteed by the C standard to be contiguous and in order, so subtracting the value of the digit 0
will 'convert' any digit to its actual, numerical value.