Rejecting inputted duoubles for switch statement?

Hello everyone,

I am using a switch statement for a simple ATM style program. It needs 4 options for the menu:

(1) Menu 1
(2) Menu 2
(3) Menu 3
(X) Exit

while (Input != 'X')

switch (Input)
{
case '1':
std::cout << "Blah blah blah" << std::endl;

etc.

When other letters are entered, the DEFAULT case gets spring, but not doubles. Hitting 1.25 will get the other numbers stuck in the buffer and input in the next prompt (not good).

Help!

Thanks!
One quick and easy solution would be to use a std::string and getline() for the input from the user, then use the first character of the string in your switch statement.

1
2
3
4
5
6
   std::sttring input;

   getline(cin, input);

   switch(input[0])
   {
Thanks for the reply. Is there a less quick and easy solution? I have another menu where only ints can be calculated (think quantity of items dispensed) and doubles make it freak.
Use the same basic method, but use a stringstream to process the string.

1
2
3
4
getline(cin, input)
stringstream sin(input);
int value = 0; // Be sure to initialize this variable, to prevent problems.
sin >> value;


With the above code if a user enters anything other than a number value will be unchanged. If they enter any number it will take the integer part and discard any remaining characters.

Topic archived. No new replies allowed.