Write a function that reads words from an input stream and stores them in a vect
ID: 3629565 • Letter: W
Question
Write a function that reads words from an input stream and stores them in a vector. Use that function both to write programs that count the number of words in the input and to count how many times each word occurred. The function should be compiled separately, i.e. placed into a separate file (read_words.cpp) and the function’s interface should be placed into yet another file (read_words.hpp).Please please~~~~
Explanation / Answer
First, create a header that declares the shared function’s signature. #ifndef GUARD_read_words_h #define GUARD_read_words_h #include #include #include std::istream& read_words(std::istream& is, std::vector& words); #endif GUARD_read_words_h Next, implement the read_words function in a source file. #include "read_words.h" using std::istream; using std::string; using std::vector; istream& read_words(istream& in, vector& words) { if (in) { words.clear(); string word; while (in >> word) { words.push_back(word); } in.clear(); } return in; } Now the programs can use this implementation. The first program will create a vector of strings and call read_words, passing cin and the vector as parameters. The populated vector will return the number of words it contains from its size() function. #include "read_words.h" #include #include #include using std::cin; using std::cout; using std::endl; using std::string; using std::vector; int main() { vector words; coutRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.