tags:

views:

89

answers:

3

Hi everyone:

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 it 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.

A: 

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.

Pablo Santa Cruz
A: 

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.

Péter Török
thank you, Pablo Santa Cruz and Péter Török.But one thing confused me was that the argument's type is char *,how to put the argument into s[]?
dennisyuan
@dennis, `char[]` __degrades_ into `char*` whenever needed. This means in practice that the underlying memory representation of the two are practically the same, and you can use the two notations interchangeably most of the time. The exception is, you can't reassign an array, i.e. `s = argv[1]` results in a compilation error. If you want to copy the _content_ of `argv[1]`, use `strcpy` as you mentioned.
Péter Török
A: 

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;
}
Iulian Şerbănoiu
I edited a little mistake in the code
Iulian Şerbănoiu