0

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;
}
ChrisD
  • 674
  • 6
  • 15
user6470814
  • 23
  • 1
  • 5

2 Answers2

3

Your conversion is wrong you should do

char charDigit = '0' + digit;// to convert it to char

See this post for a detailed explanation

I also created an Ideone snippet here

Community
  • 1
  • 1
M.M
  • 2,254
  • 1
  • 20
  • 33
1

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.

Keith M
  • 853
  • 10
  • 28
  • No, there is no ASCII involved in either of the conversions in this answer. The first is just an integer conversion, and the second is required to work for every supported character set, regardless of how the character set encodes `'0'`. – Pete Becker Aug 26 '16 at 00:11
  • @PeteBecker Maybe technically correct, but OP is almost surely using ASCII, and is using it as a character, not a number, in `total = count(stringNumber.begin(), stringNumber.end(), charDigit);`, so I think you're being a little too pedantic... – Keith M Aug 26 '16 at 15:48
  • @PeteBecker I've edited the answer for clarity regardless, see if that's what you meant by your comment. If not you'll need to explain yourself another way please – Keith M Aug 26 '16 at 16:18