How to implement an “ENTER” case into a switch statement

假装没事ソ 提交于 2019-12-11 05:22:23

问题


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.


回答1:


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();
//     }


来源:https://stackoverflow.com/questions/58700258/how-to-implement-an-enter-case-into-a-switch-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!