-
Array of functions?
Normally I can find answers just by searching, this time however I think the question is a little too simple. I need to build an array of functions (pointers I think).
Code:
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <ctype.h>
void func1();
void func2();
void func3();
int main(){
using namespace std;
//I don't know whow to make the next line work..
functions[3] = {func1, func2, func3};
int slct;
while(slct != 9)
{
system("cls");
cout << "\t\t Menu:\n\n\t 1) Function 1\n\t 2) Function 2\n\t " <<
"3) Function 3\n\n 9) Exit\n\n Please enter your selection: ";
switch(slct)
{
case 1:
case 2:
case 3:
slct --;
functions[slct]();
break;
case 9:
cout << "Thank you!";
break;
default:
cout << "I'm sorry that is not a valid choice.";
break;
}
}
return 0;
}
func1(){
cout << "This is func1.";
}
func2(){
cout << "This is func2.";
}
func3(){
cout << "This is func3.";
}
Ok, so I'm not the sharpest knife... Got to learn somehow.
Thanks
-
You can't have an array of functions, only an array of pointers to functions.
Just so you know...you didn't fill out the cases in your switch statement.;)
Also, system() is the devil because it's system dependent, slow, and unreliable.
And your cout statement that's all one line with a bunch of '\n's is kind of nasty looking. You might want to use the preferred 'endl' and seperate those output commands into lines of their own for better readability.
-
The long way
Code:
void (*functions[3])(void) = {func1, func2, func3};
The easy way (use a typedef to simplify)
Code:
typedef void (*fnptr)(void);
fnptr functions[3] = {func1, func2, func3};
-
Thanks all. Yea, I wasn't too worried about the cout,,, just trying to get the idea down. Question: If not system() how??? I use "cls" a lot, and "pause" more than I should. I know I can pause the program with a simple function, but I don't know another way to clear the screen.
-