Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please complete the following programs utilizing C++ format Growing a vector usi

ID: 3626249 • Letter: P

Question

Please complete the following programs utilizing C++ format

Growing a vector using push_back
Write a program that reads in words from the user and stores them in a vector until the user enters the sentinel word, done. The program should then ask the user for a letter and output all of the words that begin with that letter. Do not store the sentinel word done.

Sample run (user input is bold):

Enter words (enter the word done to quit):

Every man dies, not every man really lives. done

Enter a letter: m

man man

Sample run (user input is bold):

Enter words (enter the word done to quit):

The difference between the right word and the almost right word is the difference between lightning and a lightning bug. done

Enter a letter: b

between between bug

Explanation / Answer

Here's the solution to the problem that you've posted. Let me know if you have any questions.

Cameron

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main ()
{
    vector <string> allWords;    // holds all of the words
    string word;            // holds the word we are currently building
    int i;                // needed for traversal
    char letter;            // needed for letter choice

    word = "";    // needed to set up the while loop
    while (word != "done") {
        while (!isalpha(cin.peek())) {    // if its not a letter, just throw it away
            cin.get();
        }
        while (isalpha(cin.peek())) {    // while it's a letter, add it to the word string
            word += cin.get();
        }
        if (word != "done") {    // if it's not the sentinel, add it to the vector
            allWords.push_back(word);
            word = "";
        }
    }
    cout << "Enter a letter: ";
    cin >> letter;
    for (i = 0; i < allWords.size(); i++) {
        // the if statement is assuming case insensitive. For example if the user enters 'b' for the letter, this will print words that start with B or b. If this is not desired, remove the tolower from both sides of the ==.
        if (tolower(allWords[i][0]) == tolower(letter)) {
            cout << allWords[i] << " ";
        }
    }
    cout << endl;
    return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote