user6470814
user6470814

Reputation: 23

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

Upvotes: 0

Views: 127

Answers (2)

Keith M
Keith M

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

M.M
M.M

Reputation: 2304

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

Upvotes: 3

Related Questions