How to receive a arg from command line in C
I want to write a program to receive a argument from command line. It's like a kind of atof().
There my program goes:
9 char s[] = "3.1415e-4";
10 if (argc == 1) {
11 printf("%e\n",atof(s));
12 }
13 else if (argc == 2) {
14 //strcpy(s, argv[1]);
15 printf("%e\n",atof(argv[1]));
16 }
1.should I just use argv[1] for the string to pass to my atof(), or, put i开发者_如何学Pythont into s[]?
2.If I'd better put it in s[], is there some build-in function to do this "put" work? maybe some function like strcpy()??
thanks.
I personally would do it this way:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
const char defaultStr[]="3.1415e-4";
const char *arg = NULL;
if(argc <= 1)
{
arg = defaultStr;
}
else
{
arg = argv[1];
}
printf("%e\n", atof(arg));
return 0;
}
There is no need for put it into s
. Just use argv[1]
.
Having said this, is you are putting it into s anyway (which is not that bad) make sure you change your code to:
char s[20];
strcpy(s, argv[1]);
Using strcpy
with a constant char array is not a good idea.
You can simply pass it as argv[1]
, no need to copy it. Should you want to copy it, you need to ensure that s
can actually hold the full string contained in argv[1]
, and allocate a bigger array if not... so it is messier.
精彩评论