Jin Nguyen
Jin Nguyen

Reputation: 45

switch statement C++ [default part]

I'm writing a basic program about switch statement. The menu of 5 selections, if the use input invalid number, the user should be prompted again to make a selection (range is from 1-5). Here what I got so far:

#include <iostream>
#include "Menu.h"
using namespace std;

void Menu::inputChoices()
{
    int choice;

    cout << "IHCC Computer Science Registration Menu" << endl;
    cout << "1. Welome to Computer Programming in C++" << endl;
    cout << "2. Welcome to Java Programming" << endl;
    cout << "3. Welcome to Android Programming" << endl;
    cout << "4. Welcome to iOS Programming" << endl;
    cout << "5. Exit" << endl;
    cout << "\nEnter your selection: " << endl;

    while ((choice = cin.get()) != EOF)
    {
        switch (choice)
        {
        case '1':
            cout << "Welcome to Computer Programming in C++" << endl;
            break;
        case '2':
            cout << "Welcome to Java Programming" << endl;
            break;
        case '3':
            cout << "Welcome to Android Programming" << endl;
            break;
        case '4':
            cout << "Welcome to iOS Programming" << endl;
            break;
        case '5':
            cout << "Exiting program" << endl;
            break;
        default:
            cout << "Invalid input. Re-Enter your selection: " << endl;
        }
    }
}

This project has 3 files, this is the source file. My problem is when I input a number is in the range (1-5), the default part of switch still also shows up. I just want show up my selection. Can anyone help me please! Thank you very much

Upvotes: 1

Views: 260

Answers (2)

vcp
vcp

Reputation: 962

The enter key '\n' should be handled. Try following and see if it works:

while ((choice = cin.get()) != EOF)
{
  case 1:
  // ...
  // Basic idea is read extra `\n` and ignore it. Use below if condition
  default:
        if(choice != '\n')
          cout << "Invalid input. Re-Enter your selection: " << endl;
}

Upvotes: 0

rgajrawala
rgajrawala

Reputation: 2188

The reason why you are also getting the default value is because cin.get() is reading the newline character (10).

I don't think using cin.get makes sense here since entering something like 23987928 or asdasf will output a ton of lines... You should use cin >> choice and convert your cases into ints. Something like:

cin >> choice;
switch (choice)
{
    case 1:
        cout << "Welcome to Computer Programming in C++" << endl;
        break;
    // ...
    default:
        cout << "Invalid input. Re-Enter your selection: " << endl;
}

Upvotes: 2

Related Questions