简体   繁体   中英

Number of vowels in string of characters C++

I am trying to write a program that asks prompts the user to enter a sequence of characters. It can be one word or a whole sentence. I have written code where it corrrectly counts the number of vowels when it is one word, but how would I write it so that it counts the vowels in a whole sentence?

The code I have right now:

int main() {
    // Write your main here
    // var
    string word;
    int sum = 0;
    int count = 0;

    // Prompt user to enter a character
    cout << "Enter a sequence of characters: " << endl;
    cin >> word;
    cout << endl;

    int length = word.length();
    for(int i = 0; i < length; i++)
    {
        if (isVowel(word[i]))
        {
            sum += 1;
            count++;
        } // if
    } // for loop

    cout << "There are " << sum << " vowels." << endl;

    return 0;
}

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

Right now if I input: This is a sentence. The ouput will be: There are 1 vowels. I know that I have to change string word to char word, but then I don't know how I would use that to count the number of vowels.

You can easily just change cin >> word; to getline(cin, word); . It's in C++ standard library. It will read your input until the first new line. (Enter)

There are a number of ways you can approach this problem. In order to be able to find the vowels in more than a single word, you must first read more than a single word as input. cin stops reading characters when it encounters the first whitespace . So you cannot read more than a single word using cin >> word . Instead, use getline to read an entire line of text, eg

    std::string line;                   /* string to hold each line */
    ...
    std::cout << "enter characters: ";  /* prompt, read, validate line */
    if (!getline (std::cin, line)) {
        std::cerr << "error: input failure.\n";
        return 1;
    }

After reading an entire line of text, you can either use an auto-ranged for loop to loop over each of the characters checking whether each is a vowel, or you can use some of the other tools C++ provides to help you count vowels instead. .find_first_of() allows finding the first character within a designated set within a string. See cppreference std::string - find_first_of . Conveniently, find_first_of returns the position within the original string where the matching character was found, which can be incremented and used to find the next vowel, eg

    const std::string vowels = "AEIOUaeiou";  /* vowels */
    size_t n = 0, nvowels = 0;          /* positon and vowel counts */
    ...
    /* loop until vowel not found in remaining substring */
    while ((n = line.find_first_of (vowels, n)) != std::string::npos) {
        nvowels++;  /* increment vowel count */
        n++;        /* increment n to one past current vowel */
    }

( note: the offset within the string 'n' returned by .find_first_of() is incremented by +1 to index the next character after the current vowel for the next call)

Adding an output to identify each vowel and the position within the input string where it was found, you could do something similar to:

#include <iostream>
#include <iomanip>
#include <string>

int main (void) {

    std::string line;                   /* string to hold each line */
    const std::string vowels = "AEIOUaeiou";  /* vowels */
    size_t n = 0, nvowels = 0;          /* positon and vowel counts */

    std::cout << "enter characters: ";  /* prompt, read, validate line */
    if (!getline (std::cin, line)) {
        std::cerr << "error: input failure.\n";
        return 1;
    }
    std::cout << '\n';

    /* loop until vowel not found in remaining substring */
    while ((n = line.find_first_of (vowels, n)) != std::string::npos) {
        nvowels++;  /* increment vowel count */
        std::cout << "  vowel[" << std::setw(2) << nvowels << "] '" << 
                    line[n] << "' at " << n << '\n';
        n++;        /* increment n to one past current vowel */
    }

    std::cout << "\n" << nvowels << " vowels in input string.\n";
}

Example Use/Output

$ ./bin/vowel_find_first_of
enter characters: A quick brown fox jumps over the lazy dog

  vowel[ 1] 'A' at 0
  vowel[ 2] 'u' at 3
  vowel[ 3] 'i' at 4
  vowel[ 4] 'o' at 10
  vowel[ 5] 'o' at 15
  vowel[ 6] 'u' at 19
  vowel[ 7] 'o' at 24
  vowel[ 8] 'e' at 26
  vowel[ 9] 'e' at 31
  vowel[10] 'a' at 34
  vowel[11] 'o' at 39

11 vowels in input string.

There are probably a half-dozen ways to put the tools C++ provides together to count vowels. This is just the first second that popped to mind, not doubt there are better ways to do it.

Look things over and let me know if you have any questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM