Using a variable literally

D

David Hutto

In the following I would like to know how I can convert the cin(in
getline, or using cin directly) for function into a type that uses the
variable 'function', with an actual call to the function display?

So if I enter display ("string here") at the cin prompt it will call
display() and cout string a.

#include <iostream>
#include <string>
using namespace std;

int display (string a)
{cout << a;}

int main()
{
string function;

cout << "< ";
getline(cin,function);
function;



return 0;
}


Thanks,
David
 
F

Frederik Van Bogaert

In the following I would like to know how I can convert the cin(in
getline, or using cin directly) for function into a type that uses the
variable 'function', with an actual call to the function display?

So if I enter display ("string here") at the cin prompt it will call
display() and cout string a.

#include<iostream>
#include<string>
using namespace std;

int display (string a)
{cout<< a;}

int main()
{
string function;

cout<< "< ";
getline(cin,function);
function;



return 0;
}


Thanks,
David

There is no simple and elegant way to do this in C++ (that I know of),
for the simple reason that C++ is a compiled language, not an
interpreted one like perl, python or lua.

One option is to maintain a mapping of strings to function pointers,
that is, something like std::map<std::string,int (*)(std::string)>.
Then, you can look up which function corresponds to the one provided by
the user, and call it.
This method has some obvious drawbacks, one of which is that all of the
functions that can be 'called' by the user must have the same method
signature.

The second option is to embed a scripting language in your program. Lua
and python both provide hooks that allow you to embed the scripting
language in your C++ program, and to allow commands in that scripting
language to call your C++ functions.
For more information, see:

http://docs.python.org/c-api/
http://www.lua.org/manual/5.1/manual.html#3

HTH,
Frederik
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top