开发者

Accessing command line arguments in C

please forgive me if this is a noob question, but i'm a beginner at C, learning only for a while. I tried to write a program that sums up two numbers (provided as params to the application). The code is like this:

#include <stdlib.h>
#include <stdio.h>

int main( int argc, char** argv)
{
   int a = atoi(argv[0]);
   int b = atoi(开发者_JAVA百科argv[1]);
   int sum = a+b;
   printf("%d", sum);
   return 0;
}

But I get incorrect results - huge numbers even for small inputs like 5 and 10. What is wrong here?


The first argument to the program is the name of the program itself. Try using the following instead.

int a = atoi(argv[1]); 
int b = atoi(argv[2]); 


Thats because argv[0] is the name of your executable.

You should use argv[1] and argv[2].

And make sure the count (argc)is 3.


You'll want to use argv[1] and argv[2].

The first element in argv (argv[0]) is the command itself. This will be your program executable name...


Assuming the name of your program is noob.c and you compile it with gcc ./noob.c -o noob. You have to make these changes.

int a = atoi(argv[1]); 
int b = atoi(argv[2]);

You have to run it ./noob 1 2 and voila the output will be 3.

argc is 3 viz number of command line arguments, your input will be the 1st and 2nd values from the command line.


That's because argv[0] is the program name, not the first argument (i.e. if you run myapp 4 5, argv becomes myapp, 4, 5).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜