Reputation: 7941
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
Upvotes: 2
Views: 2098
Reputation: 12538
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).
Upvotes: 2