user6470814 user6470814 - 3 months ago 20
C++ Question

Search for Char in String

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;
}

M.M M.M
Answer

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