0

I am starting to write a command line converter and the only concern I have is user input (rest wont be hard). The program will have few commands like (convert 2 m to km), so when the user enters that, the program will output the converted value. My question is, what is the best way to parse user input and determine the command that user entered?. Should I divide user input into array of words and then pass to a function, so it can do something or there is another way?

3
  • Do you have some sort of syntax in mind at all? Commented May 30, 2013 at 21:42
  • Might start with tokenizing the input line. Commented May 30, 2013 at 21:45
  • Yes, I have some ideas but I don't think I can explain or write anything at this moment Commented May 30, 2013 at 21:47

3 Answers 3

1

I have written a few types of "simple parsers" (and several more advanced ones). From what you describe, if the commands are "convert 2 m to km", then you would simply need to split things on spaces.

Of course, if you allow "convert2mtokm" and "convert 2m to km" it gets a bit more difficult to deal with. Sticking to a "strict rule of there has to be a(t least one) space between words" makes life a lot easier.

At that point, you will have a vector<string> cmd that can be dealt with. So for example:

if (cmd[0] == "convert")
{
    convert(cmd); 
}

... 

void convert(vector<string> cmd)
{
    double dist = stod(cmd[1]);
    string unit_from = cmd[2]; 
    string unit_to = cmd[4]; 
    if(cmd[3] != "to")
    {
         ... print some error ... 
    }
    double factor = unit_conversion(unit_from, unit_to);
    cout << "that becomes " << dist * factor << " in " << unit_to << endl;
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you only have a few commands, it will be best to just strtok(input, ' '), which just splits up a string into an array of words in the command (assuming your command words are all separated by spaces). Then you can do some simple if/switch checks to see which command the user entered. For a larger number of commands (where some may be similar), you will probably need to implement or at least write out a DFA (deterministic finite automata).

Comments

0

An array of structures will be fine. The structure may be like this:

struct cmd
{
    char **usrcmd;
    void (*fc)();
};

Then you just have to iterate the array and compare the user input and the usrcmd[0] field (I assume the command is the first word).

However this solution is not the best way to go if you have a lot of user commands to handle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.