辅音计数程序不返回辅音数量

时间:2014-12-09 15:17:51

标签: c++ string char compare

该程序应该将辅音列表与用户输入的字母列表进行比较,并打印出用户输入中的辅音数量。但是,它只打印0.我对C ++很新,并且没有找到逻辑错误的经验。

#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int counter(char *, char);
int main()
{
  const int size = 51;
  char input[size];
  const char consonants[22] = "bcdfghjklmnpqrstvwxyz";
  cout << "Enter your letters." << endl;
  cin >> input;
  cout << consonants << "appears";
  cout << counter(input, consonants[22]) << "times" << endl;
}

int counter(char *strPtr, char ch)
{
  int times = 0;

  while (*strPtr != '\0')
  {
    if (*strPtr == ch)
        times++;
    strPtr++;
  }

  return times;
}

3 个答案:

答案 0 :(得分:1)

三个问题:

  • 您没有传递辅音数组,而是传递单个字符
  • 您传递的是无效字符(一个超过辅音数组的末尾)
  • 您正在计算无效字符存在的次数。

要解决此问题,请确保将数组作为第二个参数传递,并添加嵌套循环以迭代该数组。

答案 1 :(得分:1)

我知道你是C ++的新手,这看起来像是为了学习而进行的某种练习,但我会发布这个答案,这样你就可以看到如何使用一些C ++标准来完成功能

使用算法中的find函数

string test = "Hello world";
string vowels("aeiuo");     // Its much easier to define vowels than consonants.
int consonants_count = test.length();  // Assume all letters are consonants.

for (auto &c : test)  // for each character in test
{
    if (find(vowels.begin(), vowels.end(), c) != vowels.end()) // If c is founded inside vowels ...
    {
        consonants_count--; // Decrement the number of consonants.
    }

}

使用正则表达式

#include <regex>

string test = "Hello world";                 // A test string.
regex re("a|e|i|o|u");                       // Regular expression that match any vowel.
string result = regex_replace(test, re, ""); // "Delete" vowels.
cout << result.length() << endl;             // Count remaining letters.

答案 2 :(得分:0)

你的函数counter如果用char检查输入char并将它与一个char(ch)进行比较。

您需要在consonants数组中的所有字符上运行计数器功能,或更改counter函数:

int count = 0

for(int i = 0; i < 22 ; i ++)
{
   count += counter(input, consonants[i])
}

现在更好的方法是计算非辅音字符,然后length-count

#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int counter(char *, char);
int main()
{
  const int size = 51;
  char input[size];

  cout << "Enter your letters." << endl;
  cin >> input;
  cout << consonants << "appears";
  cout << counter(input) << "times" << endl;
}

int counter(char *strPtr)
{
  int times = 0;
  int length = 0;
  const char consonants[5] = "aeoui";
  while (*strPtr != '\0')
  {
    for(int i = 0; i < 5 ; i ++)
    {
        if (*strPtr == consonants[i])
            times++;
        strPtr++;
        length++;
    }
  }

  return length-times;
}