user12322544
user12322544

Reputation:

How to implement an "ENTER" case into a switch statement

I am working on a class project where I have to create an ordering system for a coffee shop in C++. If it is applicable, I'm working in Visual Studio.

In the project outline, the teacher said that there is a simple integer input to navigate the menu; however, he specifies that if NOTHING is inputted (I'm assuming what I've seen called a "hot enter") that it calculates the receipt and the program resets.

I have tried cin.get() and checking if the buffer is '\n', and this works fine, but my current implementation seems to only be able to capture a hot enter, and fails to roll into the switch case.

For getting input from the user, I've currently tried this:

        // Get menu input
        if (cin.get() == '\n') {    // Check if user hot entered, assign value if so
            input = 0; 
        } else {                    // If not, do it normally
            input = cin.get();
        }

However this does not work quite right, and fails to capture inputted integers for use in the switch case. I'm unsure if this sort of implementation is sound in reasoning, or whether there is a much simpler route to have a case for a hot enter.

I don't receive any errors, so I imagine there is something wrong with my understanding of how these functions work, or my implementation is flawed in its logic.

Thank you.

Upvotes: 1

Views: 422

Answers (1)

Farhad Rahmanifard
Farhad Rahmanifard

Reputation: 688

You used cin.get() twice. The second cin.get() in input = cin.get(); is redundant.

// Get menu input
    input = cin.get();
    if (input == '\n') {    // Check if user hot entered, assign value if so
        input = 0; 
    } 
//else {      // If not, do it normally
//         input = cin.get();
//     }

Upvotes: 2

Related Questions