【发布时间】:2013-02-12 02:58:06
【问题描述】:
我整天都被这个程序卡住了。我终于觉得我真的很接近了。我必须找到字符串中元音和字符的数量。然后在最后输出它们。但是,当我编译我的程序时崩溃了。我检查了语法,整天都在看我的书。如果有人可以提供帮助,我将不胜感激!因为我还有 5 个类似的函数要编写来操作 c 字符串。谢谢!
#include <iostream>
#include <string>
using namespace std;
int specialCounter(char *, int &);
int main()
{
const int SIZE = 51; //Array size
char userString[SIZE]; // To hold the string
char letter;
int numCons;
// Get the user's input string
cout << "First, Please enter a string (up to 50 characters): " << endl;
cin.getline(userString, SIZE);
// Display output
cout << "The number of vowels found is " << specialCounter(userString, numCons) << "." << endl;
cout << "The number of consonants found is " << numCons << "." << endl;
}
int specialCounter(char *strPtr, int &cons)
{
int vowels = 0;
cons = 0;
while (*strPtr != '/0')
{
if (*strPtr == 'a' || 'A' || 'e' || 'E' || 'i' || 'I' || 'o' || 'O' || 'u' || 'U')
{
vowels++; // if vowel is found, increment vowel counter
// go to the next character in the string
}
else
{
cons++; // if consonant is found, increment consonant counter
// go to the next character in the string
}
strPtr++;
}
return vowels;
}
【问题讨论】:
-
*strPtr == 'a' || 'A' || 'e' || 'E' || 'i' || 'I' || 'o' || 'O' || 'u' || 'U'将始终为真,因为'A'不为 0。 -
我不确定我是否理解,因为在检查“/0”时,空终止符。
-
您是否正在从该表达式中寻找任何特定的
bool条件?提示:*strPtr == 'a' || *strPtr == 'A' || *strPtr == 'e'.....。完成所有输入后,将其扔掉,将所有测试字符放入单个字符串常量 (const char vowels[] = "aAeEiIoOuU";) 并将表达式更改为if (strchr(vowels, *strPtr)) -
哦。好的,所以我不应该使用 or ||因为它搜索所有的元音?喜欢为每个字符使用 switch 语句吗?
-
@user2063325,就我个人而言,我会使用
std::count_if,但这可能是不允许的。请参阅我的答案,了解与多个条件进行比较的正确方法。
标签: c++ function pointers arguments c-strings