views:

632

answers:

4

Ok the output is supposed to look like this:

./a 3 4 8 2  
3  
4  
8  
2

This is what I have so far, but I am lost and can only get the first integer to print (we have to use GetInt, which gets the specified integer in the string):

int main (int argc, char*argv []){  
   int v;    
   int i;  
   i = 1;  
   v = GetInt(argc, argv, i + 1);  

   if(argc >= 1){  
      printf("%d\n", GetInt(argc, argv, i));  
   }  
   return 0;  
}
+3  A: 

Looks like you need to use a for-loop to get each value in turn.

Blorgbeard
A: 

Use printf() in a loop. argc is the number of white space separated arguments in argv[], in the example above, argc = 5.

Donotalo
argc is actually 5 (4 args + 1 for program name). :)
Nick Presta
oh right. thanks for pointing out the mistake. :)
Donotalo
+2  A: 

Without actually seeing your implementation of GetInt, something like this (Assumes C90):

#include <stdio.h>

int GetInt( int argc, char* argv[], int i ) {
    /* 
     * you may want to use sscanf, strtol or other functions,
     * but you haven't specified
     */
    return atoi( argv[i] );
}

int main ( int argc, char* argv[] ) {
    int i;
    for ( i = 1; i < argc; ++i ) {
        printf( "%d\n", GetInt( argc, argv, i ) );
    }
    return 0;
}

Returns:

$ ./a.out 3 4 8 2
3
4
8
2

Error checking omitted and such. It is an exercise to you to figure out how to deal with non-decimal arguments.

Nick Presta
More idiomatic use of the loop: for (i = 1; i < argc; i++) -- obviously, not initializing i as it is declared. Alternatively (C99), declare i in the loop as in C++: for (int i = 1; i < argc; i++) ...
Jonathan Leffler
Thanks! lol, apparently I skipped the chapter on for loops...
Kaity
Plz do not post code for homework. Just point to the right direction e.g. suggest to use loop.
qrdl
@qrdl : whether a question is homework or not is irrelevant - we should still answer it in the most complete way.
Isaac Waller
+1  A: 

As a note, why do you have to use GetInt()? It's completely superfluous and not part of a standard library, and unless you wrote it yourself (or in class), I can't imagine ever using it. This is what I would do:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;
    for(i = 1; i < argc; i++)
      {
        printf("%s\n", argv[i]);
      }
    return 0;
}

I know it doesn't use GetInt(), but it's shorter, and you probably shouldn't be using GetInt() because it's kind of useless. Plus, there's already an atoi() function and, if you don't want to use that because it's outdated, a strtol() function you can recast as an int if you have to.

I'm not citicizing you or anything, I'm just wondering why you're being required to use this superfluous, nonstandard function.

Chris Lutz