c++ - 通过循环c ++将单个字符与字符串中的字符进行比较的问题
问题描述
我正在尝试学习 c++,其中一项任务是向用户询问一个字母 - 然后询问一个文本字符串并计算第一个字母在文本字符串中重复的次数。
我编写了一些代码,成功地达到了要求字母和文本字符串的地步——我可以同时显示
我可以遍历文本字符串,计算字符串中有多少个字母。当我尝试添加一个 if 检查以比较循环内字符串中的当前字母与第一个要求的字母时 - 我收到此编译错误:
error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
if (textToCount[i] == letterToCount)
这是我写的完整代码
char getLetterToCount(char letterToCount[]);
char getTextToCount(char textToCount[]);
int countLetters(char letterToCount[], char textToCount[]);
int main()
{
char letterToCount[1];
getLetterToCount(letterToCount);
char textToCount[256];
cin.ignore();
getTextToCount(textToCount);
countLetters(letterToCount, textToCount);
return 0;
}
char getLetterToCount(char letterToCount[])
{
cout << "Enter a letter: ";
cin >> letterToCount;
}
char getTextToCount(char textToCount[])
{
cout << "Enter text: ";
cin.getline(textToCount, 256);
}
int countLetters(char letterToCount[], char textToCount[])
{
int numChrsInString = 0;
int numTimesChrtoCountrepeated = 0;
for (int i = 0; textToCount[i] != '\0'; i++)
{
if (textToCount[i] == letterToCount)
{
numTimesChrtoCountrepeated++;
}
}
cout << "num chrs in string: "
<< numChrsInString
<< "num times chr counted: "
<< numTimesChrtoCountrepeated
<< endl;
}
我做了相当多的输出来尝试找出这些问题出了什么问题——我把它的代码拉出来了,因为它让它变得更混乱了。
但是编译错误解释了什么是错误的,我只是不明白为什么它是错误的,因为我试图比较的东西都是文本字母......
如果知道 C++ 的人可以解释我做错了什么,那就太好了
解决方案
您正在将 achar
与指向char
Use 的指针进行比较:
if (textToCount[i] == letterToCount[0])
~~~
注意:很少有明显的挑剔,但以上是主要的编译器错误原因
推荐阅读
- javascript - 无法在 React App 中进行身份验证以超过 Github api 速率限制
- javascript - 如果没有网络连接,Service Worker (sw.js) 应始终返回 offline.html 文档
- angular - 无法使用角度日期饼图在 ag 网格中格式化日期
- r - R:向数据框添加 0
- wordpress - 将博客添加到托管在 Wordpress 上其他地方的 Azure Web App(反向代理)
- python - 有没有办法从 Anaconda 提示符访问 .py 文件中的变量?
- node.js - Firebase:如何在一个查询中更新和获取相同的文档?
- vb.net - 是否有写入/导出列表/类项目值的功能?
- java - 绑定到已经运行的服务
- rust - 是否可以从 lib.rs 调用 main.rs 中定义的函数?