使用指针传递C字符串参数
Using Pointers to pass C-String arguments
我整天都在这个程序上。我终于觉得我离得很近了。我必须找出字符串中元音和字符的数量。然后在最后输出它们。然而,当我编译我的程序时会崩溃。我检查了语法,整天都在看书。如果有人能帮忙,我将非常感激!因为我还有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::string
或std::getline
,并且您必须假设用户输入的字符少于51个。
你的崩溃源于:
while (*strPtr != '/0')
空字符是转义码。'/0'
是具有实现定义值的多字符文字。这意味着它可能永远都是真的。更改为:
while (*strPtr != ' ') //or while (strPtr)
除此之外,你的元音检查还有一个逻辑错误。你必须对照每个元音进行检查,比如:
if (*strPtr == 'a' || *strPtr == 'e') //etc.
如果将每个字符的toupper
或tolower
版本进行比较,将比较次数减少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;
}
相关文章:
- c++ 构造函数 将 1 个字符串参数转换为 3 个属性
- 对函数的 out 字符串参数使用 swap 与赋值
- sscanf() 有两个字符串参数
- isPalindrome不显示输出,isPalindrome函数未使用字符串输入作为字符串参数进行测试
- 如何通过C++在Python函数中传递字符串参数
- 将字符串参数传递给 ifstream
- Pybind11:将字符串*参数传递给构造函数
- 为什么我不能提供一个字符串参数来打印 ncurses?
- 为什么将char*传递给字符串参数会产生汇编错误
- 字符串参数常量字符* 和常量 wchar_t*
- 无法将字符串参数传递到构造函数中?
- 为什么对字符串参数的常量引用可以采用字符串文字?
- C 中的模板专业化中的字符串参数
- 如何使用单声道嵌入将字符串参数传递给 c# 方法
- 如何检查谷歌模拟中作为空指针传递的字符串参数
- 向 const 字符串参数发送 0 int 文本时的访问冲突
- 构造函数字符串参数未设置窗口标题
- C++ 重构采用 int 或字符串参数的方法
- 调用具有字符串参数direct vs variable的函数
- 如何使用 2 个字符串参数从 jni java 库调用