Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++; Is there a way to get my Switch function to reject a valid and invalid answer together?

So I’ve been learning how to use the "switch" statement recently. I decided to do some practice exercises. The code I show in my sample code below is one I came up with myself as a solution for a "Cola Machine" beginner exercise I found on a website "cplusplus". The exercise problem text can be found as a multi-line comment at the top of my code. Though, I did decide to try to make my code do more than what was required of the exercise.

For the most part, this code works exactly how I want it to. At first I even struggled to figure out how to get the code to repeat the user input in the line switch (cin.get()), if they had entered an invalid answer, but I solved this issue by nesting the "switch" statment inside of a "for" statement, for (int x = 0; x < 1; x++), and having the invalid answers decrement the counter ( x--; ). Not sure if that’s a practical solution, but it’s the one I came up with.

The only time my program doesn’t run as intended is when a multiple character input that contains both valid answers and invalid answers is entered into the program (i.e. "-1" or "17"). The latter example outputs the statement for only the valid part of the answer, the statement for case ‘1’, where as the former example outputs the statements for invalid answers and valid answers, so the default case and case ‘1’. Example for input "-1"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m wondering if that’s just a problem that is inherent to using using "switch" statements in general, or if there’s a practical solution I’ve yet to learn. I’m using a book to learn how to code, "C++ How To Program" by H.M. Deitel/P.J. Deitel, and they had given me a sample code for a letter grade counting program that can be found in my previous question on here. And I found that this same problem occurs in that sample code.

I’d be happy to hear any and all solutions, thank you ! 🙂

/* Write a program that presents the user w/ a choice of your 5 favorite beverages (Coke, Water, Sprite, ... , Whatever).
Then allow the user to choose a beverage by entering a number 1-5.
Output which beverage they chose.

>> Modify the program so that if the user enters a choice other than 1-5 then it will output "Error. choice was not valid, here is your money back." */

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
     string drink1 = "Water", drink2 = "Coke", drink3 = "Pepsi",
        drink4 = "Orange Juice", drink5 = "Powerade";

     string choose_text = "\n\nChoose your preferred drink: ", chosen_text = "\nYou have chosen: ";

     cout << "1.) " << drink1.append(17 - drink1.length(), ' ') << "2.) " << drink2.append(17 - drink2.length(), ' ')
         << "3.) " << drink3.append(17 - drink3.length(), ' ') << "4.) " << drink4.append(17 - drink4.length(), ' ')
         << "5.) " << drink5.append(17 - drink5.length(), ' ') << choose_text;

    for (int x = 0; x < 1; x++) {
        switch (cin.get()) {
            case '1':
                cout << chosen_text << drink1 << endl;
                break;

            case '2':
                cout << chosen_text << drink2 << endl;
                break;

            case '3':
                cout << chosen_text << drink3 << endl;
                break;

            case '4':
                cout << chosen_text << drink4 << endl;
                break;

            case '5':
                cout << chosen_text << drink5 << endl;
                break;

            case '\n': case ' ':
                x--;
                break;

            default:
                cout << "\nError. Choice was not valid.\nPlease enter an option 1 - 5." << choose_text;
                x--;
                break;
        }
    }

    return 0;
}

>Solution :

You can do this:

int answer;
cin >> answer;

That will retrieve an integer value from the user instead of a single character. That solves part of your problem.

Now, let’s look at your loop. Ick. Let’s try this:

bool keepWorking = true;

do {
     keepWorking = false;

     int answer;
     cin >> answer;
     switch (answer) {
         ...
         set keepWorking to true on the bad answers
       
     }
} while (!cin.eof() && keepWorking);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading