C Modify FunctionTablecpp so each that each function returns
C++
Modify FunctionTable.cpp so each that each function returns a string(instead of printing out a message) and so that this value is printed inside of main().
//: C03:FunctionTable.cpp
// Using an array of pointers to functions
#include <iostream>
using namespace std;
// A macro to define dummy functions:
#define DF(N) void N() { \\
cout << \"function \" #N \" called...\" << endl; }
DF(a); DF(b); DF(c); DF(d); DF(e); DF(f); DF(g);
void (*func_table[])() = { a, b, c, d, e, f, g };
int main() {
while(1) {
cout << \"press a key from \'a\' to \'g\' \"
\"or q to quit\" << endl;
char c, cr;
cin.get(c); cin.get(cr); // second one for CR
if ( c == \'q\' )
break; // ... out of while(1)
if ( c < \'a\' || c > \'g\' )
continue;
(*func_table[c - \'a\'])();
}
}
Solution
#include <iostream>
using namespace std;
// A macro to define dummy functions:
//#define DF(N) void N() { \\
cout << \"function \" #N \" called...\" << endl; }
//DF(a); DF(b); DF(c); DF(d); DF(e); DF(f); DF(g);
string DF(char s)
{
if(s==\'a\')
return(\" A is called\");
if(s==\'b\')
return(\" B is called\");
if(s==\'c\')
return(\" C is called\");
if(s==\'d\')
return(\" D is called\");
if(s==\'e\')
return(\" E is called\");
if(s==\'f\')
return(\" F is called\");
if(s==\'g\')
return(\" G is called\");
}
//void (*func_table[])() = { a, b, c, d, e, f, g };
int main()
{
while(1)
{
cout << \"press a key from \'a\' to \'g\' \"
\"or q to quit\" << endl;
char c, cr;
string ss;
cin.get(c); cin.get(cr); // second one for CR
if ( c == \'q\' )
break; // ... out of while(1)
if ( c < \'a\' || c > \'g\' )
continue;
cout<<DF(c)<<endl;
//(*func_table[c - \'a\'])();
}
}

