Link to home
Start Free TrialLog in
Avatar of elikhater
elikhater

asked on

argument passing not working properly

I am new to c. Something in my arguments is not making mush sense. I have the following:
int main (int argc, char *argv[])
.
.
n=1;
while(argv[n]>""){
i=atoi(argv[n]);
printf("%i",i);
.
.
I execute by giving program name followed by 1 or 2. when 1, it prints 1, when 2, nothing happens. Can someone provide some help? Thanks
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Hi elikhater,

The argument passing is fine.  The problem is in your test.  Also, you re-use the index variable.  Very dangerous thing to do.

Try starting with this:

  int n;

  for (n = 1; n < argc; n++)
  {
    printf("%s\n",argv[n]);
  }

Then you can expand it to:

  int n;
  int i;
  for (n = 1; n < argc; n++)
  {
    i = atoi (argv[n]);
    printf ("%d\n", i);
  }



Good Luck!
Kent
Avatar of elikhater
elikhater

ASKER

Kent, still did not work. Works fine for 1 but not 2.
try the following:

int n=1;
while(argv[n] != "")
{
int i=atoi(argv[n++]);
printf("%i",i);
}
ASKER CERTIFIED SOLUTION
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Kent,

Please clarify the following:

What is the purpose of getchar()? Aren't all the arguments stored in the argv pointer?
> What is the purpose of getchar()?

On Windows systems, clickable console apps bring up a console window,
execute and the console window disappears before you can see the output.
Windows programmers often add a call to getchar() at the end of their
console programs.  This blocks, waiting for input on stdin, so that you can
see the output.  Press any key an the window disappears.  It is not necessary
if you use Unix/Linux or run the program from an MS-DOS command window.

Although common in the Windows world, it is a horrible kludge that cripples
the use of pipes to chain multiple programs together.

kdo,

figured it out and it was relating to not adding \n to my printf statements. Thanks for your efforts in any case.