使用strcmp()后无输出

时间:2018-02-02 23:46:50

标签: c++ c-strings

我试图创建一个程序,要求用户输入一个字符串,然后使用c字符串检查字符串中有多少元音和辅音。现在我正在研究计算元音的功能。我终于得到了它,因为我没有任何错误,但我的程序在选择计算元音后就会挂断。这是我的代码。

#include "stdafx.h"
#include <iostream>
#include <string.h>

using namespace std;

class VowelsandConsonants {

public:
int findVowels(char *cString, const int STRINGLEN) {
    const int SIZE = STRINGLEN;
    int vowelCount = 0;

    char *str = cString;
    char vowels[5] = { 'a', 'e', 'i', 'o', 'u' };

    for (int i = 0; i < SIZE; i++) {
        str[i];
        for (int j = 0; j < SIZE; i++) {
            vowels[j];
            if (strcmp(vowels, str)) {
                vowelCount++;
            }
        }
    }

    return vowelCount;
}


};

int main()
{
char *myString = nullptr;
const int STRLEN = 20;
int selection;

myString = new char[STRLEN];

VowelsandConsonants v;

cout << "Enter a string 20 characters or less." << endl;
cin.getline(myString, STRLEN);

cout << "Select the number of what you want to do." << endl;
cout << "1.) Count the number of vowels." << endl;
cout << "2.) Count the number of consonants." << endl;
cout << "3.) Count both vowels and consonants." << endl;
cout << "4.) Enter another string." << endl;
cout << "5.) Exit program." << endl;

cin >> selection;

if (selection == 1) {
    cout << v.findVowels(myString, STRLEN);
}


delete[] myString;

return 0;
}

我是以正确的方式接近这个吗?

1 个答案:

答案 0 :(得分:-3)

我建议使用包含元音的C风格字符串,然后使用strchr进行搜索:

const char vowels[] = "aeiou";
const size_t length = strlen(cString);
unsigned int vowel_count = 0;
for (unsigned int i = 0; i < length; ++i)
{
    if (strchr(vowels, cString[i]) != NULL)
    {
        ++vowel_count;
    }
}

还有其他方法,例如使用数组来保存计数(并使用字母作为索引)或std::map