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

Using Pointers to pass C-String arguments

本文关键字:字符串 参数 指针      更新时间:2023-10-16

我整天都在这个程序上。我终于觉得我离得很近了。我必须找出字符串中元音和字符的数量。然后在最后输出它们。然而,当我编译我的程序时会崩溃。我检查了语法,整天都在看书。如果有人能帮忙,我将非常感激!因为我还有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'是具有实现定义值的多字符文字。这意味着它可能永远都是真的。更改为:

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

除此之外,你的元音检查还有一个逻辑错误。你必须对照每个元音进行检查,比如:

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

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

while (*strPtr != '/0')

应为:

while (*strPtr != 0)

while (*strPtr != '');

你的编译器没有警告你吗?如果是这样,不要忽视警告。如果没有,请获得更好的编译器。

另请参阅其他比较中有关错误的注释。

其他答案应该可以解决您的问题,我可以建议您编写单独的函数而不是一个全能的函数吗?

bool IsSpecialChar(char c)
{
 switch(c)
 {
    case 'a':
    case 'A':
    case 'e':
    case 'E':
    case 'i':
    case 'I':
    case 'o':
    case 'O':
    case 'u':
    case 'U':
    return true;
 }
   return false; 
}

int specialCounter(char *strPtr, int &cons)
{
  int vowels = 0;
  cons = 0;
  while (*strPtr != '')
  {
    IsSpecialChar(*strPtr) ? vowels++ : cons++;
    strPtr++;
  }
  return vowels;
}