C++函数重载无法识别字符
C++ function overloading cannot identify char
当我输入两个整数时,输出是正确的它们的差异。但是,当我输入字符串和字符时,它不是返回字符串中字符出现的次数,而是返回 -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();
}
这些更改应该可以修复它。
相关文章:
- c++为什么ifstream get()函数返回无法识别的特殊字符
- 字符串数组C++中的字符识别不正确
- 识别数字的字符
- 从文件阅读时未识别的字符
- 字符串中的重复字符是否可以在 O(n) 中识别和量化
- 识别C 程序中的空间字符
- 您如何使用字符串或字符在C 中识别名称识别变量
- C++函数重载无法识别字符
- 如何让编译器识别这些字符
- 试图将字符串作为类的参数传递,但在C++中它被识别为字符数组
- 我可以't识别if语句中的endl字符
- 用于识别回文字符数组的递归函数
- 无法识别以空结尾的字符
- 如何简单地使用无法识别的字符
- 标记字符串,识别字符时出错
- 在if语句中识别为9的8个字符
- 使字符数组在输入时识别空格
- Python/ c++ /Java:是否有一个库可以识别字符并告诉我它们在图像中的位置
- 程序无法识别字符
- 我试图在 C++ 的字符串中找到所有"#"字符并用 "hash" 替换它们,但正则表达式无法识别字符"#"