Reputation: 51
So I am attempting to read in values from the command land after a flag has been hit. I don't want to use scanf
because it shouldn't pause. It should take in arguments as follows:
run -p 60 10
Where 60 is a percentage value, and 10 is a number of processes. How does one go about reading those into variables without using scanf which pauses for user input? Do I need to assign them values using argv[2]
and argv[3]
? I want integer values, not strings.
This is my code so far:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
bool Gamble(int percent);
int main(int argc, char *argv[])
{
int c;
int pflag = 0;
int vflag = 0;
int percent;
int processes;
while ((c = getopt (argc, argv, "-p-v: ")) != -1)
{
switch (c)
{
case 'p':
pflag = 1;
percent = argv[2];
//scanf("%d", &percent);
break;
case 'v':
vflag = 1;
break;
default:
processes = argv[3];
}
}
printf("%d\n", percent);
printf("%d\n", processes);
Gamble(percent);
return 0;
}
P.S. Gamble is just a class that takes in the percentage, generates a random number, and returns "Success" or "Failure" based on whether or not the percentage passed is hit using the random generator.
Upvotes: 0
Views: 275
Reputation: 1838
getopt puts the option values in optarg. You don't want to read them from argv[] directly.Ssee examples of how to use getopt
http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html
Upvotes: 1