Search code examples
d

Skipping first argv in DLang array


I am starting to learn D. I wrote a few basic programs (hello world... add 2 numbners) and I'm on to my third. It should take an array of numbers and add them together. I have the following code:

import std.stdio;
import std.algorithm;
import std.string;
import std.conv;

int main(string[] argv)
{
    int sum;
    foreach (int i, string s; argv) 
    {
        writefln("argv[%d] = '%s'", i, s);
        if (isNumeric(s)){
            sum += to!int(s);
        } else {
            writeln("Please only input numbers. ex:\n\t", argv[0], " [number] [number] [number]");
            return 1;
        }
    }
    writeln(sum);
    return 0;
}

The issue I am having is that argv[0] is the script name.

  1. Why?

  2. How do I tell it to skip the first one? I could just tell it to skip all non-numeric inputs, but maybe I'd want to error out if the index is greater than 0?


Solution

  • argv[0] is always the name by which the program was called, it is part of the C standard that D inherited. It is useful if you have a single program that can be called by multiple names on the command line - it helps you know what the user wanted as one program might be several commands (see the C program busybox for a big example of that, the one program contains several common unix commands). You can also use it for the help screen, like you did.

    The reason it is part of args is that the command line is like: program foo bar - the program name is the first thing given on that line, so it is the first thing in args too.

    But to skip it, you can just slice it off before the loop:

    foreach (int i, string s; argv) 
    

    Can become

    foreach (int i, string s; argv[1 .. $]) 
    

    Though, then i will be offset too - i == 0 when argv == 1, so you might want to just say if(i == 0) continue; in the loop as well to skip it.