我正在尝试学习 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++的人能解释一下我做错了什么就太好了
最佳答案
你正在比较一个 char
和一个指向 char
的指针
使用:
if (textToCount[i] == letterToCount[0])
~~~
注意:有一些明显的挑剔,但以上是主要的编译错误原因
关于c++ - 通过循环c++将单个字符与字符串中的字符进行比较的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53245798/