ingroxd
ingroxd

Reputation: 1025

How to process command line arguments?

Yesterday I made a simple program in c++ that uses the arguments passed through command line.

E.G. myDrive:\myPath\myProgram.exe firstWord secondWord

The program run fine and do what it has to, but there's a little curiosity I have: I had to write argc --; before I could use it well, otherwise I have a run-time crash [The compiler won't speak!].

In particular argc gives me a bad time when I don't give any word as argument to the program when I run it...

Now it works, so isn't bad at all, but I wonder why this is happening! [P.S. making argc --; and printing it, it gives 0 as value!]

EDIT: Here all the istructions that use argc

int main(int argc, char *argv[]) {
    [...]
    argc --;
    if(argc > 0){
        if(firstArg.find_last_of(".txt") != string::npos){
            reading.open(argv[1], ios::binary);
            [...]
        }
    }
    if ((!(firstArg.find_last_of(".txt") != string::npos)) && argc > 0){
    [...]
        for(int i = 1; i <= argc; i ++){
        [...]
        toTranslate = argv[i][j];
        [...]
        toTranslate = argv[i][j];
        }
    }
}

Upvotes: 1

Views: 476

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477600

The arguments include the name of the program itself as well, so argc is always at least 1.

Here's the typical loop:

int main(int argc, char * argv[])
{
    for (int i = 0; i != argc; ++i)
    {
        std::cout << "Argument #" << i << ": " << argv[i] << "\n";
    }
}

Alternatively you can print backwards:

while (argc--)
{
    std::cout << argv[argc] << "\n";
}

Upvotes: 5

Related Questions