user2953119
user2953119

Reputation:

Printing arguments passed through the command line

I tried to print the arguments passed through the command line as follows:

#include<iostream>

int main(int argc, char ** argv)
{
    std::cout << argv[0] << std::endl;
    std::cout << argv[1] << std::endl;
    std::cout << argv[2] << std::endl;
}

but failed. The output was:

./a.out
first
second

DEMO

It wasn't what I expected. I expected something like that:

first
second
__some_garbage_data__    

Is the binary name always treated as an argument with the index 0?

Upvotes: 0

Views: 592

Answers (5)

Andreas DM
Andreas DM

Reputation: 10998

argv[0] not only shows the name of file but also shows you the path, exmaple if you run the program without having changed the directory to the programs directory an output like below would show up(windows):

C:\Users\username\desktop\program.exe.

On linux, like your example outputs ./a.out where ./ represents current directory.

Upvotes: 0

Sourav Kanta
Sourav Kanta

Reputation: 2757

arg[0] stores name of program called and after that argv stores the arguments that were passed in the command line.

$./a.out hello hi

 0     1   2

So

 argv[0]=a.out
 argv[1]=hello
 argv[2]=hi

Upvotes: 0

sertsedat
sertsedat

Reputation: 3600

In most languages the first argument is the program itself. In your case, argv[0] will always print ./a.out

Upvotes: 1

Martin Petkov
Martin Petkov

Reputation: 420

Whenever you call your program from the command line, its 0th argument is going to be the name of the file/command itself. So basically, the arguments you have passed are from the first member of the array onwards.

If you include

cout << argv[3]

you will get what you are expecting.

Upvotes: -1

Barry
Barry

Reputation: 303057

Yes, that is expected behavior. From [basic.start.main], emphasis mine:

If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (ntmbs s) (17.5.2.1.4.2) and argv[0] shall be the pointer to the initial character of a ntmbs that represents the name used to invoke the program or "". The value of argc shall be non-negative. The value of argv[argc] shall be 0.

Upvotes: 2

Related Questions