C++ function overloading cannot identify char

When I input two integers, the output is correctly their difference. However when I enter a string and a char, instead of returning how many times the char appears in the string, it returns -1, which is the out put for error. Could anyone please help me? It's just my second day learing c++...

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>

void mycount(int a, int b)
{
        std::cout<< a - b <<std::endl;
}

void mycount(char str[], char s[])
{
        int len,i;
        int sum=0;

        len = strlen(str);
        for (i=0;i<len;i++){
            if (strncmp(&str[i],&s[0],1) == 0){
            sum = sum + 1;

};
};
printf("results: %d times\n",sum);
}

int main()
{
        int a,b;
        char c[200],d;
        if(std::cin>> a >> b){
            mycount(a,b);
        }
        if(std::cin>> c[200] >> d){
            mycount(a,b);
        }
        else{
            std::cout<< "-1" <<std::endl;
        }
        std::cin.clear();
        std::cin.sync();
}

Answers


Hint - what will this program print?

#include <iostream>

using namespace std;

int main()
{

    char c[200],d;

    cout << sizeof(c) << endl;
    cout << sizeof(d) << endl;

   return 0;
}

Answer:

200

1

That declaration does not do what you think it does - c is an array of 200 chars, d is a single char. It's a feature of the C declaration syntax, same as:

int *c, d;

c is a pointer to int, d is an int.

Since you are doing C++, why not make your life easier and use std::string instead?


A few changes should fix your problems. First when inputting an array with cin use getline and call ignore right before hand. I find it easier to pass s as a char instead of an array of size one make sure your call your second my count with c and d instead of a and b.

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>

void mycount(int a, int b)
{
        std::cout<< a - b <<std::endl;
}

void mycount(char str[], char s)
{
        int len,i;
        int sum=0;

        len = strlen(str);
        for (i=0;i<len;i++){
            if (strncmp(&str[i],&s,1) == 0){
            sum = sum + 1;

};
};
printf("results: %d times\n",sum);
}

int main()
{
        int a,b;
        char c[200],d;
        if(std::cin>> a >> b){
            mycount(a,b);
        }
         std::cin.ignore();
        if(std::cin.getline (c,200) && std::cin >> d){
            mycount(c,d);
        }
        else{
            std::cout<< "-1" <<std::endl;
        }
        std::cin.clear();
        std::cin.sync();
}

These changes should fix it.


Need Your Help

How do I reset a tabcontoller with a drill down table view

iphone detailsview tableview tabbarcontroller

I have a tabbar with one of the tabs containing a drilldown table.

Spring JSP variable not assigned

spring jsp jsp-tags

I have in my JSP page code like this: