how to use getopt

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
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.
It worked well if i type ./hello -t 3. But if i add -n bob, it doesnt work
Repeat: not "nt:", but "n:t:" (colon after n and after t)
I did change it and it is still now working
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
Thank you so much!
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?
> 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.