0

I realise this question probably has been asked before. I'm asking this as I don't know what to search for.

Hi, so I've started learning about arrays, but I'm not sure how (or if) they can help me with this problem:

Let's say I want the user to be able to choose what to do within my program. I then write a numbered list to the console:

  1. Output "a"
  2. Output "b"
  3. Output "c"

The user will be asked to enter a number, and the number defines which function the program is going to run. What i want the program to do is instead of having me write this three times and changing out the numbers and letters:

if (numberInput == "1") {
functionA;
}

I just write something that takes the number from numberInput and then runs the function associated with it.

Again, I know this question probably has been asked a 1000 times before, so I'm wondering if someone has an idea on how I should go forward on searching for the answer. Thanks!

  • 2
    It sounds like you want a `std::map ` because you want to map integers to functions. – David Schwartz Sep 07 '17 at 16:49
  • At some level you will likely still have to enter some type of mapping between integer and function for as many functions you will have the user execute this way whether you are initializing a map (or some other container), using a switch or individual if statements. – drescherjm Sep 07 '17 at 16:50
  • Maybe read up on `if()` statements. – Galik Sep 07 '17 at 18:33

2 Answers2

1

What you want is called a switch statement

I would start there

Tyler
  • 955
  • 9
  • 20
0

i think best here is switch/case stuff

exactly what you're askin about is to use array of function pointers.See How can I use an array of function pointers?

you'll end up with

int c;
std::cin >> c;
....
(*fnpointers[c])();