getopt() and weird output

This is a discussion on getopt() and weird output within the C Programming forums, part of the General Programming Boards category; I'm fairly new to the getopt function and anything it involves. At the moment I'm trying to write a simple ...

  1. #1
    UNIX chick
    Join Date
    Mar 2003
    Posts
    92

    getopt() and weird output

    I'm fairly new to the getopt function and anything it involves. At the moment I'm trying to write a simple application that has two parameters and additional arguments. The problem is that the output from one of the variables (parm) is only a bunch of strange symbols. Here's the code:
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    extern char *optarg; 
    extern int optind;
    extern int optopt;	
    extern int opterr;
    extern int optreset;
    
    int main(int argc, char *argv[]){
    
        int command;
        char cmnd[25];
        char parm[25];
    
        while((command = getopt(argc, argv, "c:p:")) != -1) {
    
            switch(command) {
    
                case 'c':
                    strcpy(cmnd, optarg);
                    break;
    
                case 'p':
                    strcpy(parm, optarg);
                    break;
    
                case '?':
                default:
                    break;
            }
    
            printf("command: %s\n", cmnd);
            printf("parameter: %s\n",  parm);
    
        }
        return 0;
    }
    And here's an example of an output:
    Code:
    ./printArgs -c test -p TEST
    command: test
    parameter: ??P????P
    command: test
    parameter: TEST
    Something is obviously not correct here, help highly appreciated.

  2. #2
    UNIX chick
    Join Date
    Mar 2003
    Posts
    92
    It works very well, thank you. However, my intention with putting the printf()'s outsite the switch was with (re)use of the variables in mind. The printf()'s were only there temporarily so I could see that everything worked as it should - which it didn't. Bottom line is that I need to get the printf()'s working, so I know the variables contain the right values (or am I off track?). Sorry for beeing unclear.

  3. #3
    UNIX chick
    Join Date
    Mar 2003
    Posts
    92
    Wow, awesome, thanks.
    The code looks a bit 'unfamiliar' to me, so I migh't come up with a few questions about it when I have examined it a bit more. Thanks again.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21