How to provide users with options to input

Hi.I am trying to make a game in which the computer will ask the player which ship it wants to user by providing him with 5 options. How can I do it?
learn about the syntax "cin"

This is what you need. I suggest googling a tutorial on "cin" and "int/char/double"
This is how I coded it. There would be other ways of doing it. But I personally think functions are the way to go here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
using namespace std;


void redShip()
{
    
}
void blueShip()
{
    
}
void greenShip()
{
    
}
void whiteShip()
{
    
}
void blackShip()
{
    
}

int main()
{
    int option = 0;

    cout << "1. RED SHIP" << endl;
    cout << "2. BLUE SHIP" << endl;
    cout << "3. GREEN SHIP" << endl;
    cout << "4. WHITE SHIP" << endl;
    cout << "5. BLACK SHIP" << endl;
    cout << "Please choose a number: ";
    cin >> option;
    
    switch (option)
    {
        case 1:
            redShip();
            break;
        case 2:
            blueShip();
            break;
        case 3:
            greenShip();
            break;
        case 4:
            whiteShip();
            break;
        case 5:
            blackShip();
            break;
    }
}
Last edited on
@Radar

Just a little advice that might come in handy in the future:

It's quite a good idea to always provide a default: case for your switch, so you can catch bad input. If your user entered 6 in your program, then your program would just end. There are compiler options that produce warnings whenever there is no default case in a switch.

I would also provide case that allows the user to quit.

You could also make the type of the option variable unsigned short. Even better use an enum (as you said, another way of doing it). A C++11 scoped enum allows one to put in a type. There are compiler options that produce warnings when not all the values of the enum are accounted for as cases in the switch.
http://en.cppreference.com/w/cpp/language/enum


With the enum, I would not put Ship in the name of the enum, just have the Colours, that one can use it for other things that have colours.

Finally, try to avoid having using namespace std; there is plenty written about why that is bad - Google it.

Hope all is going well at your end :+)

Topic archived. No new replies allowed.