2013-02-12 24 views
0

我一直被困在这个程序中。我终于觉得自己越来越近了。我必须在字符串中找到元音和字符的数量。然后在最后输出它们。但是,当我编译我的程序崩溃。我检查过语法,并整天看着我的书。如果有人可以帮助,我会非常感激!因为我有5个更类似的函数来编写操纵C字符串。谢谢!使用指针传递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; 

} 
+7

'* strPtr =='a'|| 'A'|| 'e'|| 'E'|| '我'|| '我'|| 'o'|| 'O'|| 'u'|| 'U''将永远是真实的,因为''A''不是0. – chris 2013-02-12 03:00:09

+0

我不确定我是否理解,因为在检查'/ 0'时,空终止符。 – neganando 2013-02-12 03:02:14

+1

你是否在寻找来自该表达式的任何特定'bool'条件?提示:'* strPtr =='a'|| * strPtr =='A'|| * strPtr =='e'.....'。当你完成所有的输入后,把它扔出来,把所有的测试字符串放在一个字符串常量中('const char vowels [] =“aAeEIIoOuU”;')并将你的表达式改为'if(strchr(元音, * strPtr))' – WhozCraig 2013-02-12 03:02:15

回答

3

我会假设你限制在不使用std::stringstd::getline,并且你必须假定用户输入的东西少于51个字符。

你崩溃源于:

while (*strPtr != '/0') 

一个空字符转义码。 '/0'是一个具有实现定义值的多字符文字。这意味着它可能永远是真的。将其更改为:

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

除此之外,您的元音检查出现逻辑错误。你必须检查它针对每个元音,就像这样:

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

你会发现它更容易,如果你比较反对touppertolower版本的每个字符以2

的因素,以减少比较的数量
2
while (*strPtr != '/0') 

应该是:

while (*strPtr != 0) 

while (*strPtr != '\0'); 

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

另请参阅您的其他比较中有关错误的评论。

+0

是的,它没有给我一个警告。 :/。我不敢相信我的斜线会走错路。非常感谢! – neganando 2013-02-12 03:09:32

2

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

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 != '\0') 
    { 
    IsSpecialChar(*strPtr) ? vowels++ : cons++; 
    strPtr++; 

    } 
    return vowels; 
}