http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
Chapter 8 // Exercise 12
12. Improve print_until_s() from section 8.5.2. Test it. What makes a good set of test cases? Give reasons. Then, write a print_until_ss() that prints until it sees a second occurrence of its quit argument.
#include "stdafx.h" #include "std_lib_facilities.h" void print_until_s(const vector<string> &v, string quit) { //for every 's' in 'v' for (string s : v) { if (s == quit) return; cout << s << " "; } } int main() { vector<string> words = { "this", "is", "the", "ultimate", "showdown", "of", "ultimate", "destiny", "good", "guys", "bad", "guys", "and", "explosions", "as", "far", "as", "the", "eye", "can", "see" }; print_until_s(words, "and"); cout << '\n' << endl; keep_window_open(); return 0; }
I made the vector a const pointer as we aren't modifying any values and generally formatted it to a style that I prefer (it really annoys me when the bracket starts on the same line as the argument). As for testing, this works quite well but stops at the first instance of the word, which is a given. It also prints the entire vector if no quit word is found.
#include "stdafx.h" #include "std_lib_facilities.h" void print_until_ss(const vector<string> &v, string quit) { int quitFound = 0; //for every 's' in 'v' for (string s : v) { if (s == quit) ++quitFound; else if (quitFound == 2) return; cout << s << " "; } } int main() { vector<string> words = { "this", "is", "the", "ultimate", "showdown", "of", "ultimate", "destiny", "good", "guys", "bad", "guys", "and", "explosions", "as", "far", "as", "the", "eye", "can", "see" }; print_until_ss(words, "ultimate"); cout << '\n' << endl; keep_window_open(); return 0; }
Thank you, your solutions are great but I took quite a trait of perfectionist as programmer and this program will truly quit upon second occurrence of quit-word. So what's wrong with it? Nothing really, this program does exactly what it was asked for to the dot however I thought that maybe stroustrup meant something like ";", ";" or ";;" instead of ";", "Perfectionist", ";" which quits program immediately. Anyways big thanks!
ReplyDeleteI'm not quite sure I understand what you mean? Test with punctuation? In my re-do:
Deletehttps://github.com/l-paz91/principles-practice/blob/master/Chapter%208/Exercise%2012
I slightly changed it so it goes for however many instances of the quit string you like but it still compares full strings, not substrings for things like punctuation.