I l@ve RuBoard |
![]() ![]() |
Exercise 1.8The switch statement of Section 1.4 displays a different consolation message based on the number of wrong guesses. Replace this with an array of four string messages that can be indexed based on the number of wrong guesses. The first step is to define the array of string messages in which to index. One strategy is to encapsulate them in a display function that, passed the number of incorrect user guesses, returns the appropriate consolation message. Here is a first implementation. Unfortunately, it is not correct. Do you see the problems? const char* msg_to_usr( int num_tries ) { static const char* usr_msgs[] = { "Oops! Nice guess but not quite it.", "Hmm. Sorry. Wrong again.", "Ah, this is harder than it looks, isn't it?", "It must be getting pretty frustrating by now!" }; return usr_msgs[ num_tries ]; } The index is off by one. If you flip back to the Section 1.4 switch statement, you'll see that the number of incorrect tries begins with 1 because, after all, we are responding to wrong guesses on the user's part. Our array of responses, however, begins at position 0. So our responses are always one guess more severe than called for. There are other problems as well. The user can potentially try more than four times and be wrong with each try, although I capped the number of unique messages at 4. If we unconditionally index into the array, a value of 4 or greater will overflow the array boundary. Moreover, we must guard against other potential invalid values such as a negative number. Here is a second iteration. I've added a new first message in case the user somehow has not yet guessed. I don't expect we'll actually return it, but in this way, the other messages at least are in their "natural" position. I defined a const object to hold a count of the number of entries in the array. const char* msg_to_usr( int num_tries ) { const int rsp_cnt = 5; static const char* usr_msgs[ rsp_cnt ] = { "Go on, make a guess. ", "Oops! Nice guess but not quite it.", "Hmm. Sorry. Wrong again.", "Ah, this is harder than it looks, no?", "It must be getting pretty frustrating by now!" }; if ( num_tries < 0 ) num_tries = 0; else if ( num_tries >= rsp_cnt ) num_tries = rsp_cnt-1; return usr_msgs[ num_tries ]; } ![]() |
I l@ve RuBoard |
![]() ![]() |