how to use getopt

Sep 1, 2014 at 12:34am
Here is my code:


#include <iostream>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

int main(int argc, char **argv)
{
char *nvalue = "World";
int c=0;
int tvalue = -1;

while ((c = getopt (argc, argv, "nt:")) != -1)
switch(c)
{
case 'n':
nvalue = optarg;
break;
case 't':
tvalue = atoi(optarg);
break;
}

for (int i = 0; i < tvalue; i++)
{
cout<<"["<<i+1<<"] Hello "<<nvalue<<"!\n";
}

return 0;
}



when I typed in cmd: ./hello -t 3 it should appear:
[1] Hello World!
[2] Hello World!
[3] Hello World!

and when type: ./hello -t 3 -n Bob it should appear:
[1] Hello Bob!
[2] Hello Bob!
[3] Hello Bob!

however, it is not working. any help please?
Last edited on Sep 1, 2014 at 12:50am
Sep 1, 2014 at 1:37am
1
2
//while ((c = getopt (argc, argv, "nt:")) != -1)
while ((c = getopt (argc, argv, "n:t:")) != -1)


And check if optarg is a null pointer.
Sep 1, 2014 at 1:41am
It worked well if i type ./hello -t 3. But if i add -n bob, it doesnt work
Sep 1, 2014 at 1:46am
Repeat: not "nt:", but "n:t:" (colon after n and after t)
Sep 1, 2014 at 1:48am
I did change it and it is still now working
Sep 1, 2014 at 2:05am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <unistd.h>
#include <cstdlib>

int main( int argc, char* argv[] )
{
    const char* nvalue = "World" ; 
    int tvalue = 1 ;
    
    int c ;
    while( ( c = getopt (argc, argv, "n:t:") ) != -1 ) 
    {
        switch(c)
        {
            case 'n':
                if(optarg) nvalue = optarg;
                break;
            case 't':
                if(optarg) tvalue = std::atoi(optarg) ;
                break;
        }
    }
    
    for( int i = 0 ; i < tvalue; ++i )
       std::cout << '[' << i+1 << "] Hello " << nvalue << "!\n" ;
    std::cout << '\n' ;   
}

http://coliru.stacked-crooked.com/a/4c075ea24e1c1055
Sep 1, 2014 at 2:10am
Thank you so much!
Sep 1, 2014 at 3:20am
And check if optarg is a null pointer.

When can optarg be null in this case? It can point to an empty string, but isn't the whole point of the colon to indicate that the argument is required?
Sep 1, 2014 at 3:59am
> isn't the whole point of the colon to indicate that the argument is required?

Does that imply: one should not guard against there being an inadvertent typo (as in the code in the original post) while specifying optstring?
http://coliru.stacked-crooked.com/a/78e6b91012721970
Topic archived. No new replies allowed.