gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:00 24 4
gpt4 key购买 nike

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

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