首页 > 解决方案 > 通过循环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++ 的人可以解释我做错了什么,那就太好了

标签: c++compiler-errors

解决方案


您正在将 achar与指向char Use 的指针进行比较:

if (textToCount[i] == letterToCount[0])
                                   ~~~

注意:很少有明显的挑剔,但以上是主要的编译器错误原因


推荐阅读