tags:

views:

129

answers:

7

How can I move away from (in c++) the annoying menus like:

(a) Do something (b) Do something else (c) Do that 3rd thing (x) exit

Basically I want to be able to run the program then do something like "calc 32 / 5" or "open data.csv", where obviously I would have written the code for "calc" and "open". Just a shove in the right direction would be great, I am sure I can figure it all out, I just need something to google-fu.

+2  A: 

What you want is a command line parser. I can't remember the name, but there is actually a design pattern to this. However, this site gives you some sample code you can use to write one. Hope that's not giving you too much of the answer :)

Chris Thompson
I'm not sure he does want a command line parser; he's wanting to input commands after the program is running.
Matthew Talbert
Ah you're absolutely right, I misread that. I know there is a design pattern for this though...
Chris Thompson
+3  A: 

I think you want to do something like this:

string cmd;
cout << "Enter your command:" << endl;
cin >> cmd;
if(cmd == "open") {
    // read file name and open file
} else if (cmd == "calc") {
    // read and evaluate expression
} ...

Though depending on how complex you want your command language to be, a more elaborate design (maybe even using a parser generator) might be appropriate.

sepp2k
A: 

Instead of looking for input like a, b, etc, just ask for generic input. Split the input at spaces, do a "switch" on the first one to match it up to your function calls, treat the rest as arguments.

Matthew Talbert
+2  A: 

You should pick up The C++ Programming Language, which is the book on C++ (there are others, but this one is great). It has an example program, spread over a few chapters, on tokenizing, parsing arguments, and making a calculator.

Chris Simmons
I have that book! (In white hardback with 2 ribbon bookmarks no less!). It was waay beyond me in the first chapter and just couldnt get into it, but it may be time to give it another go.
Silvanus
A: 

Is your menu based on a call to getchar()? If you want to allow entering an entire line before processing it, you can use fgets() or, in C++ land, std::getline.

Tim Sylvester
A: 

Some folks will package their C++ class definitions as Python classes by adding a Python interface to the C++.

Then they write the top-level interpreter in Python using the built-in cmd library.

S.Lott
A: 

Take a look to:

  • ANTLR which is a very good and easy parser which also generates code on C++.
  • You can take a look to Natural CLI (java) to get inspired. (Disclaimer: i'm the developer of that project).
FerranB