gpt4 book ai didi

c++ - 辅音计数程序不返回辅音数

转载 作者:行者123 更新时间:2023-11-30 03:58:31 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com