tags:

views:

54

answers:

2

I've run into the following problem: My console utility should be running as a process (hope it's the right term) so every command goes to it directly. Like gnuplot, interactive shells (irb, etc.).

This shows what I'm talking about:

Mikulas-Dites-Mac-2:Web rullaf$ command
Mikulas-Dites-Mac-2:Web rullaf$ irb
>> command
NameError: undefined local variable or method `command' for main:Object
    from (irb):1
>> exit
Mikulas-Dites-Mac-2:Web rullaf$

first command is executed as shell command, but after I enter irb, it's not. You get the point.

irb puts console into some special mode, or it simply parses the given input itself in some loop? Is here any proper way to create such a behavior in c++? Thanks

+2  A: 

You have to parse the input yourself. Depending on the complexity of the input, this might be accomplished by some simple string matching for trivial cases. A very simple example:

#include <iostream>
#include <string>

int main()
{
  std::string input;
  for(;;)
  {
    std::cout << ">>";
    std::cin >> input;
    if(input=="exit")
      return 0;
    else if(input=="test")
      std::cout << "Test!\n";
    else
      std::cout << "Unknown command.\n";
  }
}

Obviously, this little program will print a prompt (>>) and understand the commands exit and test and will print Unknown command. on all other commands.

For everything else, you probably want to learn some more about pattern matching or parsing; Google is your friend (take a look at bison for example and a good tutorial).

Greg S
Thanks, this is an obvious solution, yet I did want to have some more complicated commands - with dynamic number of parameters etc. Anyway, guess I'll have to write it myself.
Mikulas Dite
+1  A: 

To parse your command line, you can use Boost.Program_options.

neuro