getopt

Jan 5, 2016 at 10:57pm
Hi. I was just practicing what I have learned so far and ran into a problem.
In the code below, I simply need to accept either an -r or a -c flag. I don't need the -d flag or any arguments for -d.

This is the only way I know how to write this, but how would I *properly* write this for what I need?

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
28
#include <iostream>
#include <unistd.h>


main (int argc, char **argv){

int array[10];
int x;

while ((x = getopt (argc, argv, "rcd:")) != -1)
switch (x)
{
case 'r':
for (int i = 0; i < 10; i++){
array[i] = i;
std::cout << array[i];
}
std::cout << "\n";
break;

case 'c':

for (int i = 0; i < 10; i++){
array[i] = i;
std::cout << array[i] << "\n";
}
}
}
Last edited on Jan 5, 2016 at 11:12pm
Jan 5, 2016 at 11:18pm
Nevermind....figured it out. My problem was using :


while ((x = getopt (argc, argv, "rc")) != -1)

was what I needed.
Last edited on Jan 5, 2016 at 11:18pm
Jan 5, 2016 at 11:23pm
I'm not sure I understand your question.
You only need -r or -c.
You don't need -d or any arguments for d. (So why are do you have "d:" in your getopt string?)

x = getopt (argc, argv, "rc")

Getopt does not check or enforce exclusivity. Your program should notice that and complain appropriately.

Hope this helps.
Jan 6, 2016 at 12:58am
Silly mistake. Sorry.
Jan 7, 2016 at 12:21am
Don't be sorry. Life happens. I'm glad you got it working. :O)
Topic archived. No new replies allowed.