#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    3

    Argv[i] not printed ?? and argc is always 1?


    I've written a small code with argv and argc, but when i tested argc it showed =1 ,even when i added more commands. Also the argv isn't printed AT ALL, just the "hello world" and that's as far as it goes:

    Code:
    int main(int argc, char *argv[])
    {
    
        printf("Hello World\n\n");
        
        int i;
        for(i=1; i<argc; ++i)
            printf("%s%s", argv[i], (i<argc-1)? " " : "");
    
    getch();
    return 0;   
        
    }
    Anybody have an idea why ?
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,253
    Rep Power
    2222
    argv[0] contains the program name. argv[1] contains the first command-line argument. The value in argc includes argv[0], so argc will be one more than the number of command-line arguments.

    You say that argc is 1. That means that there are no command-line arguments. In the for-loop, since 1 is not less than 1, you never enter the loop.

    You say that you are entering arguments but they're not showing up? Tell us exactly what you type.

    C:TEST>gcc -Wall lerner3.c
    lerner3.c: In function `main':
    lerner3.c:8: parse error before `int'
    lerner3.c:9: `i' undeclared (first use in this function)
    lerner3.c:9: (Each undeclared identifier is reported only once
    lerner3.c:9: for each function it appears in.)

    C:TEST>
    You should know better by now than to ignore warnings. Your declaration for i was misplaced.

    C:TEST>a 1 2 3 4
    Hello World

    1 2 3 4
    C:TEST>
    Works for me. What were you doing differently?
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    3
    But i did declared the i as int :confused:

    I just typed the printf of hello world, and then the for loop.

    But if there is a print command, then shouldn't argc be at least 2? since 1 if for the name of the command ?

    Is it about having another program passing something to the current one? I only have this code and this is it.
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,253
    Rep Power
    2222
    Huh?

    Your declaration of i was misplaced! In C, all declarations got before any executable code, such as a call to printf. In C++ and C99 you can break that rule, but not in C.

    printf has absolutely nothing to do with argc nor with argv[].

    The command line arguments are what you type on the command line when you run the program. In what I had copy-and-pasted from my console (AKA "DOS window", AKA "Command Prompt"), a.exe was the name of the executable and I gave it four arguments which were 1, 2, 3, and 4. Those are command line arguments and those are what argc and argv[] handle. The only thing that has to do with your code is that your code will read argc and argv[] to fetch and use those command line arguments.

    Another example:
    gcc -Wall lerner3.c
    gcc is the executable, which is the GNU C compiler, gcc.
    -Wall is the first argument, which is a command option to turn display all warnings
    lerner3.c is the second argument, which is the C source file to be compiled.
    I could have given it two more arguments, -o lerner3, in which -o is the command option for giving the executable a name and lerner3.exe would be that name. Without that, it defaults to naming the executable a.exe (in Linux, it's a.out; UNIX doesn't depend on file extensions to tell it what's executable and what isn't).

    You might want to find an old MS-DOS command tutorial and spend a little time on the command line, to get a feel for what it's about. That's where I lived and worked for 14 years, 9 years with MS-DOS and 5 years on other systems.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    3
    I tried declaring i at the beginning of main and it didn't change anything.

    but still, it is declard BEFORE its first use, which occurs inside the loop:
    Code:
        int i;
        for(i=1; i<argc; ++i)
    ......
    .....
    Wait, maybe i'm just mixing here something: I don't pass anything into main since it is my only program, the only files compiled.

    I thought argc counts the commands you have in your current file ?
  10. #6
  11. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,253
    Rep Power
    2222
    What's above the declaration? A line of executable code. C89 does not allow that.

    You wrote:
    Code:
        printf("Hello World\n\n");
        
        int i;
        for(i=1; i<argc; ++i)
            printf("%s%s", argv[i], (i<argc-1)? " " : "");
    should be
    Code:
        int i;
    
        printf("Hello World\n\n");
        
        for(i=1; i<argc; ++i)
            printf("%s%s", argv[i], (i<argc-1)? " " : "");
    What you wrote would be allowed in C++ and in C99, but not in C89 which is what's universally supported in industry.

    ... and it didn't change anything.
    Well, it got rid of that error, didn't it? Unless you're using either C++ or C99.

    If you meant that it didn't magically change the behavior of argc and argv[] to something it wasn't designed to do, then of course not.

    Do you understand about command-line arguments?
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    3
    But i didn't have any error in the first place.

    >>What i understood is that i have to pass something to my main program, from another file. Otherwise nothing will be printed since it deals with OTHER files passing its commands, is that correct ?
  14. #8
  15. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,253
    Rep Power
    2222
    Originally Posted by C learner
    I thought argc counts the commands you have in your current file ?
    No. I don't think there's anything that does that outside of a program profiler (a program that collects statistics about your program).

    argc tells you how many strings are in argv[]. That's all it does.

    argv[] contains the command line that invoked this program. The entire line you type in at the command prompt is tokenized, split up at the spaces (ie, it's space-delimited) into separate strings and each string is stored in argv. If you have an argument that contains embedded spaces, then you need to surround it in quotation marks.

    Using argc and argv[], you can read the arguments that the user had typed in and use them in your program. If your program does not use any command-line arguments, then you do not need to declare argc and argv as parameters of main.
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    3
    I think i didn`t study that properly because i thought that argv was supposed to be what`s inside my main. I didn't connect it to the stuff about the operating system (i am going to use your examples in the previous answers when i read about it on the internet, since my books lack the full explanation). Thanks for helping me out :)

    I wish my book had such good explanations like yours lol. :rolleyes:
  18. #10
  19. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,253
    Rep Power
    2222
    Originally Posted by C learner
    But i didn't have any error in the first place.
    Then you might be using C99. My compilers do not support C99.

    Originally Posted by C learner
    >>What i understood is that i have to pass something to my main program, from another file. Otherwise nothing will be printed since it deals with OTHER files passing its commands, is that correct ?
    I do not understand what you mean by passing something from another file. Nor by other files passing commands. You are talking about an entirely different technology, like remote procedure calls (RPC) or Dynamic Data Exchange (DDE, which went on to spawn OLE and ActiveX). Command line arguments have nothing to do with any of that.

    I keep explaining it but each time it looks like it's sailing right over your head. Give me an example of what you are trying to do, a detailed example.

    Here's a detailed example for you about what command line arguments do.

    You open a Command Prompt window, officially called a "console". It's a shell virtually identical to the old MS-DOS command line from 1980 to 1995. To run a program, you type the name of the program, DOS finds the executable file (it has a search path that it uses if the executable is not in the current directory) and runs it. That executable name is loaded into argv[0]. If you typed more than one word (separated by spaces), then each subsequent word is stored in argv and argc is set to the total number of words you had typed in at the command line.

    During its execution, the program checks argc to see whether any arguments had been typed in and how many. Exactly what it does with that information depends on what function those arguments serve. Often, they will be the names of files that the program will either read from or write to. Another argument could be a string that you want to find in a range of files (designated by use of wildcard notation). Some arguments are required, in which case if they're missing then the program will terminate with an error after having displayed a "usage" message telling the user what it expects. Some arguments are optional, in which case if that argument is missing then a default value will be used.

    In order to learn STL, I'm working on a game server now. Here is the function that processes the command line arguments:
    Code:
    /********************************************************************/
    /* ProcessCLArgs                                                    */
    /*    Check the command line arguments for validity.                */
    /*    Read in the server port number.                               */
    /********************************************************************/
    void ProcessCLArgs(int argc,char *argv[],unsigned short *port)
    {
    
        /* First process the command-line arguments. */
        /* NOTE: for security reasons, on many systems only a privileged 
            program or user is allowed to bind to a well-known port.  
            Therefore, it will probably be necessary for you pick a high-numbered one.  */
        
        /* Test for correct number of arguments and read in parameter (if any) */
        if (argc > 2)    // if more than one argument
        {
            fprintf(stderr, "Usage:  %s [<Server Port>]\n", argv[0]);
            exit(1);
        } 
        else if (argc == 2)   // if there's one argument
            *port = atoi(argv[1]);  /* first arg:  Local port */
        else                      // there is no argument
            *port = SHIP_PORT;      /* set to default port, 7 */
    }
    I hope that helps to make it clear. Like I suggested, if you were to spend some quality time on the command line, you would have a more intuitive feel for command line arguments.

    PS
    In addition, here's the equivalent code in an echo client I had written:
    Code:
        /* First process the command-line arguments. */
        
        if (!strcmp(argv[1],"-r"))
        {
            randflag = 1;
            i1 = 2;
            i2 = 3;
            nargs = 4;
        }
        else if (!strcmp(argv[2],"-r"))
        {
            randflag = 1;
            i1 = 1;
            i2 = 3;
            nargs = 4;
        }
        else if (argc > 3 && !strcmp(argv[3],"-r"))
        {
            randflag = 1;
            i1 = 1;
            i2 = 2;
            nargs = 4;
        }
        else 
        {
            randflag = 0;
            i1 = 1;
            i2 = 2;
            nargs = 3;
        }
        
        /* Test for correct number of arguments */
        if ((argc < 2) || (argc > nargs))    
        {
            fprintf(stderr, "Usage: %s [-r] <Server IP> [<Echo Port>]\n", argv[0]);
            exit(1);
        }
    
        /* first arg: server IP address (dotted quad) */
        servIP = argv[i1];             
    
        /* second arg, if any: port number */
        if (argc == nargs)
            echoServPort = atoi(argv[i2]);   /* Use given port */
        else
            echoServPort = ECHO_PORT;  /* otherwise, use the default port number */
    The optional -r command option tells the client to repeated send a preset string to the server; this is in order to stress-test the server. The server's IP address is a required argument; we need to know to whom to connnect. The port number is optional. The echo service is normally on port 7, but the server might be allowed to bind to it (system security reasons) so a different port may have to set.
    Last edited by dwise1_aol; August 20th, 2013 at 08:54 PM.

IMN logo majestic logo threadwatch logo seochat tools logo