C++函数重载无法识别字符

C++ function overloading cannot identify char

本文关键字:识别 字符 函数 重载 C++      更新时间:2023-10-16

当我输入两个整数时,输出是正确的它们的差异。但是,当我输入字符串和字符时,它不是返回字符串中字符出现的次数,而是返回 -1,这是错误的输出。谁能帮我?这只是我学习 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 timesn",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();
}

提示 - 这个程序会打印什么?

#include <iostream>
using namespace std;
int main()
{
    char c[200],d;
    cout << sizeof(c) << endl;
    cout << sizeof(d) << endl;
   return 0;
}

答:

200

1

该声明不会像您认为的那样执行 - c 是一个包含 200 个字符的数组,d 是单个字符。这是 C 声明语法的一个功能,与:

int *c, d;

c 是指向 int 的指针,d 是 int。

既然你正在做C++,为什么不让你的生活更轻松,而使用 std::string 代替呢?

一些更改应该可以解决您的问题。首先,在输入带有cin的数组时,请使用getline并事先调用ignore。我发现将 s 作为字符传递比将大小为 1 的数组更容易,请确保您用 c 和 d 而不是 a 和 b 调用您的第二个 my 计数。

#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 timesn",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();
}

这些更改应该可以修复它。