c++ - 使用指针传递 C 字符串参数

标签 c++ function pointers arguments c-strings

我整天都卡在这个程序上。我终于觉得我真的很接近了。我必须找到字符串中元音和字符的数量。然后在最后输出它们。但是,当我编译我的程序时崩溃了。我检查了语法,整天都在看我的书。如果有人可以提供帮助,我将不胜感激!因为我还有 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;

}

最佳答案

我将假设您仅限于不使用 std::stringstd::getline 并且您必须假设用户输入的内容更少超过 51 个字符。

您的崩溃源于:

while (*strPtr != '/0')

空字符是转义码。 '/0' 是具有实现定义值的多字 rune 字。这意味着它可能总是正确的。将其更改为:

while (*strPtr != '\0') //or while (strPtr)

除此之外,您的元音检查存在逻辑错误。您必须针对每个元音检查它,如下所示:

if (*strPtr == 'a' || *strPtr == 'e') //etc.

如果您与每个字符的 touppertolower 版本进行比较,您会发现将比较次数减少 2 倍会更容易。

关于c++ - 使用指针传递 C 字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14824682/

相关文章:

c++ - 当我尝试创建对象数组时出错

c++ - 无法使用访问器设置私有(private)静态成员变量

c - "Assignment from incompatible pointer type"警告

c++ - 如何从 C++ 函数返回 const Float**

c - 程序对于 prime 和 non prime 没有按预期工作

javascript - 无法在 JavaScript 中的可变长度参数数组上运行函数

C++ 函数模板导致输入参数出错

c++ - 函数参数 : Copy or pointer?

c++ - 什么是树形小部件的视口(viewport)?

c++ - 如何在 Qt 中创建一个粗体的红色文本标签?