该程序应该将辅音列表与用户输入的字母列表进行比较,并打印出用户输入中辅音的数量。但是,它仅显示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;
}

最佳答案

我知道您是C++的新手,这看起来像是为了学习而进行的某种练习,但是我将发布此答案,以便您可以了解如何使用某些C++标准函数来完成此工作。

使用算法中的查找功能

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.

关于c++ - 辅音计数程序未返回辅音数量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27382416/

10-16 04:56