user6470814 user6470814 - 1 year ago 118
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;

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download