1

Question: How do you read multiple commands/variables/modifiers from a single line of user input?

Much like any CLI such as Command Prompt would do, the user enters a single line and variables + modifiers are read and assigned from it.

E.G. A conversion program command:

32 km to cm

Then it reads:

numToConvert = (32)

then

"km to cm"

points to conversionRate1

 conversionRate1 = (0.621371192)

multiply 32 by conversion rate (0.621371192)

print Result.

Second Example:

shutdown -h

or

shutdown /?

shutdown is read as a command

-h modifies it or /? modifies it

2 Answers 2

3

Anything given on the commandline, after the program name, is split on whitespace, and passed in to the args array.

So, given:

class Program
{
    static void Main(string[] args)
    {
        foreach (var a in args)
        {
            Console.WriteLine(a);
        }
    }
}

running "c:>program.exe convert foo to bar" will produce the lines

convert
foo
to
bar

In order to parse out the semantic meaning, you will need to scan the args array and look for the modifiers.

If you've got strict syntax, you can simply look in the expected position

var numToConvert = Convert.toint32(args[4])

If you're allowing flexible syntax it will be more complex; you will need to develop a series of parsing rules to help you make sense of the input.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Just what I was looking for. I saw something similar with .split and arrays, but I couldn't get it to do what I wanted. I looked all over and I couldn't seem to put what I wanted into all the right keywords. I do understand parsing, and excuse the informal "read-through" code. On lunch break at work. Thanks so much!
0

Additionally, you may want to look into a library designed for helping parse and manage command line arguments. Command Line Parser Library is a good option.

1 Comment

Thank you as well, I will check into it

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.