N
N
Nikolay Semenov2016-12-11 17:48:08
.NET
Nikolay Semenov, 2016-12-11 17:48:08

How to count command line arguments?

The test task contains the following paragraph:
The name of the input, output file, sorting mode, as well as the content type are set at
startup through command line arguments. Windows command line examples:
sort-it.exe in.txt out.txt -i -a (for integers in ascending order)
sort-it.exe in.txt out.txt -i -d (for integers in ascending order) descending)
sort-it.exe in.txt out.txt -s -a (for ascending lines)
I did like this:

static void Main(string[] args)
        {
            string fromfile = args[1];
            string tofile = args[2];
            string typedata = args[3];
            string sortingmode = args[4];
....................

when I run the program from the command line
sort-it.exe in.txt out.txt -i -a
it crashes with an error that the index was outside the array.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rou1997, 2016-12-11
@nickola105

First, array indexing in C# does not start at 1, but at 0, you could verify that this is true for arguments as well, by finding that it args[1]returns the second, and not the first, argument.
Secondly, in a correct way, in any case, you need to check for the presence of each argument, it may not be there, the program should not "crash", but issue a "user-friendly" error description and exit.
A test task at school or when applying for a job?
If the latter, then ... hmm, however. :)

N
Nikolay Semyonov, 2016-12-11
@nickola105

well, of course, it doesn't take the .exe file as an array element, so
string fromfile = args[0];
string tofile = args[1];
string typedata = args[2];
string sortingmode = args[3];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question