Reputation: 23
My code is returning zero instead of actually counting the number of instances of the digit that are actually in the number. I am confused about what I have done wrong.
int number_times_appear(int digit, int number)
{
int total = 0;
string stringNumber = to_string(number);
char charDigit = digit;
total = count(stringNumber.begin(), stringNumber.end(), charDigit);
cout << total;
return total;
}
Upvotes: 0
Views: 127
Reputation: 893
char charDigit = digit;
does not do what you seem to think it does. This takes the value in digit
and converts it into a character based on your character set (e.g. for American ASCII, this table). For example, a digit
of 9
could actually search your string for tabs!
You want char charDigit = '0'+digit;
instead because, to again use the example of ASCII, '0'
evaluates to 48, as per the linked table, and the numbers '1'
-'9'
follow it as 49-57.
Upvotes: 1